28. 找出字符串中第一个匹配项的下标

方法一
class Solution {
public:
int strStr(string haystack, string needle) {
if(haystack.find(needle) == string::npos){
return -1;
}
return haystack.find(needle);
}
};
方法二
class Solution {
public:
int strStr(string haystack, string needle) {
int haystackLength = haystack.length();
int needleLength = needle.length();
int haystackIndex = 0, needleIndex = 0;
while(haystackIndex < haystackLength){
if(haystack[haystackIndex] != needle[needleIndex]){
haystackIndex = haystackIndex - needleIndex;
needleIndex = 0;
}
else{
if(needleIndex == needleLength-1){
return haystackIndex-needleLength+1;
}
needleIndex++;
}
haystackIndex++;
}
return -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
class Solution {
public:
int strStr(string haystack, string needle) {
int haystackLength = haystack.size(),needleLength = needle.size();
if(needleLength == 0){
return 0;
}
vector<int> next(needleLength);
for(int i=1,j=0; i<needleLength; i++){
while(j>0 && needle[i]!=needle[j]) {
j = next[j-1];
}
if(needle[i]==needle[j]){
j++;
};
next[i] = j;
}
for(int i=0,j=0; i<haystackLength; i++){
while(j>0 && haystack[i]!=needle[j]){
j = next[j-1];
}
if(haystack[i]==needle[j]){
j++;
}
if(j==needleLength){
return i - needleLength + 1;
}
}
return -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
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40