1. 程式人生 > 其它 >leetcode28實現strStr

leetcode28實現strStr

一、題目

二、程式碼

class Solution {
public:
    int strStr(string haystack, string needle) {
        if (needle.length()==0) return 0;
        if( haystack.length()< needle.length()) return -1;
        int index = 0;
        int start = 0;
        int count = 0;
        while(index<=haystack.length()-needle.length()){
            
            
while(index<=haystack.length() && haystack[index]!=needle[0]) index++; count = 0; start = -1; for(int i=index; i<index+needle.length(); i++){ if(haystack[i] == needle[i-index]){ count++; }
else break; } if(count==needle.length()){ start = index; break; } else{ index++; } } if(count != needle.length()) start = -1; return start; } };
縱一葦之所如,臨萬頃之茫然。