Skip to content

28.Implement strStr()  #20

@niuworld

Description

@niuworld

Question:

Implement strStr().

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

Solution:

class Solution {
public:
    int strStr(string haystack, string needle) {
        int flen = haystack.length();
        int len = needle.length();
        if( len == 0 ) return 0;
        if ( flen == 0) return -1;
                int j;
         for( j = 0; j <= flen - len; ){
             int i = 0;
             while ( haystack[j] == needle[i] ){
                 i++;
                 j++;
                 if ( i == len  )
                 return j - i;
             }
             if ( i != 0)
             j = j - i +1  ;
            else 
            ++j ;
            }
         return -1;
    }
};

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions