我的方法:直接调用C++的方法。

 class Solution {
 public:
     int strStr(string haystack, string needle) {
         return haystack.find(needle);
     }
 };

 

 

别人:

for i:

i<=haystack.size()-needle.size() 结果是4ms
i<haystack.size() 结果是600ms
class Solution {
public:
    int strStr(string haystack, string needle) {
        if(needle.size()==0){
            return 0;
        }
        if(haystack.size()<needle.size()){
            return -1;
        }
        for(int i=0;i<=haystack.size()-needle.size();i++){
            int L2=needle.size();
            for(int j=0;j<needle.size();j++){
                if(haystack[i+j]==needle[j]){
                    L2--;
                    if(L2==0){
                        return i;
                    }
                }
                else{
                    break;
                }
                
            }
        }
        return -1;
    }
};

 

 

posted on 2018-04-04 20:17  苛性氢  阅读(114)  评论(0编辑  收藏  举报