459.重复的子字符串
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; // r
return false;
}
};
当一个字符串是重复的字符串构成时,那么两个同样的字符串拼在一起也是重复的,
所以定义新的字符串等于两个相加,由于要判断中间有没有重复,如果不删去头和尾,则搜出来还是原来的字符串,删去后判断即可
28.实现strStr()
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;
}
};