leetcode——28—— Implement strStr()

Implement strStr().

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

算法的复杂度是O(nm)

以后再来学习更快的算法(KMP)


class Solution {
public:
    int strStr(string haystack, string needle) {
      int m = haystack.size();
        int n = needle.size();
        for(int i = 0; i <= m-n; i ++)
        {
            int j;
            for(j = 0; j < n; j ++)
            {
                if(haystack[i+j] != needle[j])
                    break;
            }
            if(j == n)
                return i;
        }
        return -1;
  
    }
};
 
  

你可能感兴趣的:(leetcode——28—— Implement strStr())