Implement strStr()

题目:Implement strStr().

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

思路:从后向前

最难得方法是使用KMP算法,不过程序是easy级别的,应该是可以使用从前往后的算法的。效率为n的平方。

代码:

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


原文地址:https://www.cnblogs.com/jsrgfjz/p/8519895.html