【leetcode】Implement strStr()

題目:

Implement strStr().

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


分析:

看字符串needle是否是haystack的一部分。用暴力破解法。



代碼:


class Solution {
public:
    int strStr(string haystack, string needle) {
       if(needle.length()==0) return 0;
       int m=haystack.length(),n=needle.length();
       //暴力破解法:
       for(int i=0;i<m;i++){
           int k=0;
           //從某個位置i開始,連續k個值在haystack和needle裏是相同的
           while(k<n&&haystack[i+k]==needle[k]){
               k++;
           }
           //說明needle是haystack的一部分
           if(k==n) return i;
       }
       return -1;
    }
};


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章