力扣 题目28-- 实现 strStr()

题目


题解


 

一开始 不匹配所以往右移动

这时匹配成功 双方同时移动 当然上面的位置要保留要用其他变量去移动(如果双方同时移动过程中有不匹配直接break即可 然后将needle恢复至0 haystack从红色箭头继续遍历)

本来应该这时就结束了 但是因为我写的判断成功就会向右移动 所以最后应该是

 

 

即当下标相差为needle的长度时 直接返回红色箭头所在位置即可

当 needle 是空字符串时,我们应当返回0 所以加个判断

代码


 1 #include<iostream>
 2 #include<string>
 3 using namespace std;
 4 class Solution {
 5 public:
 6     int strStr(string haystack, string needle) {
 7         if (haystack == "") {
 8             return 0;
 9         }
10         int sign = 0;
11         for (int i = 0; i < haystack.size() - needle.size() + 1&& haystack.size()>= needle.size(); i++) {
12             if (haystack[i] == needle[0]) {
13                 sign = i;
14                 for (int j = 0; j < needle.size();j++) {
15                     if (haystack[sign] == needle[j]) {
16                         sign = sign + 1;
17                     }
18                     else
19                     {
20                         break;
21                     }
22                 }
23                 if (sign - i  == needle.size()) {
24                     return i;
25                 }
26             }
27         }
28         return -1;
29     }
30 };
31 int main() {
32     string haystack = "abb";
33     string needle = "bb";
34     Solution sol;
35     int num=sol.strStr(haystack, needle);
36     cout << num << endl;
37 
38 }
View Code

 

posted @ 2022-04-16 12:52  无聊的阿库娅  阅读(13)  评论(0编辑  收藏  举报