leedcode-28-implement strstr()
作者:互联网
思路:
暴力匹配法
1.遍历haystack
2.循环判断haystack[j]== needle[k]
3.输出return i (而不是return j 因为i是发现haystack[j]== needle[k]的首位置,j是匹配后最后一个位置)
代码:
class Solution { public: int strStr(string haystack, string needle) { if(needle.empty()) return 0;const int N=haystack.size()-needle.size() +1; for(int i=0;i<N;i++) { int j=i; int k=0; while(j<haystack.size() && k<needle.size() && haystack[j]== needle[k]) { j++; k++; } if(k==needle.size()) return i; } return -1; } };
标签:strstr,string,int,needle,28,return,implement,haystack,size 来源: https://www.cnblogs.com/Sunshineboy1/p/13334910.html