首页 > 其他 > 详细

leedcode-28-implement strstr()

时间:2020-07-18 14:09:20      阅读:29      评论:0      收藏:0      [点我收藏+]

思路:

暴力匹配法

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

leedcode-28-implement strstr()

原文:https://www.cnblogs.com/Sunshineboy1/p/13334910.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!