Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
两个字符串A和B, 在A中查找是否出现过B, 如果出现就返回第一次出现的下标, 如果没有就返回-1
用暴力的方法求解,假设A字符串长度为N, B字符串长度为K, 则时间复杂度是N*K , LeetCode的评价是
程序如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
class Solution { public : int strStr(string haystack, string needle) { int i=0; if (haystack.size()<needle.size()) return -1; while (1) { //边界处理 if (i>(haystack.size()-needle.size())) break ; int flag=0; //记录是否会遇到不一致的字符 int k=0; //needle的下标 for ( int j=0;j<needle.size();j++) if (needle[j]!=haystack[j+i]){ i++; flag=1; break ; } else { k++; } if (flag==0){ return i; } } return -1; } }; |