Leetcode37:implement StrStr ()

Source: Internet
Author: User

Implement strStr ().

Returns the index of the first occurrence of needle in haystack, or-1 if needle are not part of haystack.

Update (2014-11-02):

The signature of the function had been updated to return the index instead of the pointer. If you still see your function signature returns a char * or String , please click on the Reload button to reset your Code definition.

This problem is implemented in the haystack string to find the first occurrence of the needle index number. Using brute force search is relatively easy to achieve.

Class Solution {public:    int strStr (String haystack, string needle) {        int length_h = Haystack.length ();        int length_n = Needle.length ();        int step = length_h-length_n + 1;        for (int i = 0; i < step; i++)        {            int J;            for (j = 0; J < Length_n; J + +)            {                if (haystack[i+j] = = Needle[j])                    continue;                else break                    ;            }            if (j = = Length_n)                return i;        }        return-1;    }};


Leetcode37:implement StrStr ()

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.