【leetcode】Implement strStr()

来源:互联网 发布:fc2最新域名点击此处 编辑:程序博客网 时间:2024/06/16 11:28

题目:

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;
    }
};


0 0