28. Implement strStr()
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
在haystack中找与needle 第一个相匹配的位置。如果找不到,返回-1。
代码如下:
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
30
31
|
class Solution {
public :
int strStr(string haystack, string needle) {
if (haystack.size() == 0 && needle.size() == 0)
return 0;
if (needle.size() == 0)
return 0;
if (haystack.size() < needle.size())
return -1;
for ( int i = 0;i < haystack.size() - needle.size() + 1;i++)
{
bool flag = true ;
if (needle[0] == haystack[i])
{
int j = 0;
for (; j < needle.size();j++)
{
if (needle[j] != haystack[i+j])
{
flag = false ;
break ;
}
}
if (flag)
return i;
}
}
return -1;
}
};
|