一、题目描述
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
题目解读:给你两个字符串needle和haystack,找出needle在haystack第一次出现的下标,如果needle不是haystack的子串返回-1
思路:遍历haystack,找出haystack中能匹配上needle第一个字符的字符,(1)没找到这样的字符,返回-1;(2)找到了这样的字符,算一下haystack之后的字符长度是否比needle的长度短,如果短的话,返回-1。如果不短,开始遍历needle中的每个字符,和从该位置开始haystack后面的字符,看是否都相等,只要有一个不相等,就退出循环,如果都相等,返回字符串开始的位置。该过程中,需要注意记录字符串的开始位置,在退出循环后要从这个位置再继续往后遍历,不退出循环的话说明找到了这样的字符串,那么需要返回这个位置。
c++代码(6ms,23.10%)
class Solution {
public:
int strStr(string haystack, string needle) {
int len1 = haystack.size();
int len2 = needle.size();
if(len2 > len1) //如果needle的长度比haystack长,那么不可能是haystack的子串
return -1;
if(len2 == 0)
return 0;
int i,j;
for(i=0; i<len1; i++) //下标i遍历haystack,寻找能匹配上needle第一个字符的字符
{
if(haystack[i] == needle[0]) //如果匹配到了第一个字符和needle的第一个字符相等了
{
if((len1-i) < len2) //如果接下来的字符长度比needle少了,那么就匹配不上了
return -1;
else{
int tmp=i;
int flag=0;
for(j=0; j<len2;){
if(haystack[tmp] != needle[j]){
flag=1;
break;
}
else{
j++;
tmp++;
}
}
if(flag == 0){
return i;
}
}//else
}//if
}//for
return -1;
}
};
思路差不多,更简洁的一份代码(4ms)
class Solution {
public:
int strStr(string haystack, string needle) {
int m = haystack.length(), n = needle.length();
if (!n) return 0;
for (int i = 0; i < m - n + 1; i++) {
int j = 0;
for (; j < n; j++)
if (haystack[i + j] != needle[j])
break;
if (j == n) return i;
}
return -1;
}
};
使用KMP算法的一份代码,4ms
class Solution {
public:
int strStr(string haystack, string needle) {
int m = haystack.length(), n = needle.length();
if (!n) return 0;
vector<int> lps = kmpProcess(needle);
for (int i = 0, j = 0; i < m; ) {
if (haystack[i] == needle[j]) {
i++;
j++;
}
if (j == n) return i - j;
if (i < m && haystack[i] != needle[j]) {
if (j) j = lps[j - 1];
else i++;
}
}
return -1;
}
private:
vector<int> kmpProcess(string& needle) {
int n = needle.length();
vector<int> lps(n, 0);
for (int i = 1, len = 0; i < n; ) {
if (needle[i] == needle[len])
lps[i++] = ++len;
else if (len) len = lps[len - 1];
else lps[i++] = 0;
}
return lps;
}
};