28.找出字符串中第一个匹配项的下标
mydemo--(my thought)--(falied)
class Solution {
public:
int strStr(string haystack, string needle) {
for(int i=0; i<haystack.size(); i++)
{
if(haystack[i] != needle[0]) continue;
int j=0;
int start = i;
while(haystack[i]==needle[j])
{
if(j == needle.size()-1) return start;
j++;
i++;
}
}
return -1;
}
};
mydemoV2--(暴力解法,自己思路)--(successed)
class Solution {
public:
int strStr(string haystack, string needle) {
int start = 0;
int len1 = haystack.size();
int len2 = needle.size();
while(start < len1)
{
int i = start;
int j = 0;
while(haystack[i] == needle[j] && i < len1 && j < len2)
{
if(j == len2 - 1) return start;
i++;
j++;
}
start++;
}
return -1;
}
};
时间复杂度 O(n*m)
前缀:包含首字母,不包含尾字母的所有字符串
后缀:包含尾字母,不包含首字母的所有字符串
卡哥demo--KMP算法
class Solution {
public:
void getNext(int* next, const string& s){
int j = 0;
next[0] = 0;
for(int i = 1; i<s.size(); i++){
while (j > 0 && s[i] != s[j]){
j = next[j-1];
}
if(s[i] == s[j]){
j++;
}
next[i] = j;
}
}
int strStr(string haystack, string needle) {
if(needle.size() == 0) return 0;
int next[needle.size()];
getNext(next, needle);
int j = 0;
for(int i = 0; i < haystack.size(); i++){
while(j > 0 && haystack[i] != needle[j]){
j = next[j-1];
}
if(haystack[i] == needle[j]){
j++;
}
if(j == needle.size()){
return (i - needle.size() + 1);
}
}
return -1;
}
};
459.重复的子字符串
卡哥代码
KMP思路
class Solution {
public:
void getNext(int* next, const string& s){
next[0] = 0;
int j = 0;
for(int i = 1; i < s.size(); i++){
while(j > 0 && s[i] != s[j]){
j = next[j-1];
}
if(s[i]==s[j]){
j++;
}
next[i] = j;
}
}
bool repeatedSubstringPattern(string s) {
if(s.size() == 0){
return false;
}
int next[s.size()];
getNext(next, s);
int len = s.size();
if(next[len - 1] !=0 && len % (len - next[len - 1]) == 0 ){
return true;
}
return false;
}
};