LeetCode28
题目:
![](https://i-blog.csdnimg.cn/blog_migrate/105dea060d35d3515c4346f4bc047d92.png)
本人解法:(暴力永不过时!真面试就寄了)
class Solution {
public:
int strStr(string haystack, string needle) {
if(haystack.size() < needle.size()) return -1;
for(int i = 0; i <= haystack.size()- needle.size();i++)
{
int j = 0;
int m = i;
while(j < needle.size() && haystack[m]==needle[j])
{
m++;
j++;
}
if(j == needle.size())
return i;
}
return -1;
}
};
kmp解法(记不住 要多记)
class Solution {
public:
void getNext(string& s,int* next)
{
int j = -1;
next[0] = j;
for(int i = 1;i < s.size();i++)
{
while(j >= 0 && s[j + 1] != s[i])
j = next[j];
if(s[j + 1] == s[i])
j++;
next[i] = j;
}
}
int strStr(string haystack, string needle) {
if(needle.size() == 0)
return 0;
int next[needle.size()];
getNext(needle,next);
int j = -1;
for(int i = 0;i < haystack.size();i++)
{
while(j >= 0 && haystack[i] != needle[j+1])
{
j = next[j];
}
if(haystack[i] == needle[j+1])
{
j++;
}
if(j == needle.size()-1)
{
return (i - needle.size() + 1);
}
}
return -1;
}
};
LeetCode459
题目:
![](https://i-blog.csdnimg.cn/blog_migrate/d4fd29544efc481c632ab5be027910f1.png)
移动匹配:
class Solution {
public:
bool repeatedSubstringPattern(string s) {
string t = s + s;
t.erase(t.begin());
t.erase(t.end()-1);
if(t.find(s) != std::string::npos) return true;
return false;
}
};