28.实现strStr()
非KMP法:
public class Solution {
public int StrStr(string haystack, string needle) {
int k=0;
int i=0;
int ptr=0;
int cnt=0;
if(haystack.Length<needle.Length)
{
return -1;
}
for(i=0;i<haystack.Length;i++)
{
if(haystack[i]==needle[k])
{
ptr=i;
k++;
cnt++;
if(k==needle.Length)
{
return ptr-cnt+1;
}
}
else
{
if(k!=needle.Length)
{
if(i!=haystack.Length-1)
{
i=i-k;
cnt=0;
k=0;
continue;
}else
{
return -1;
}
}
}
}
return -1;
}
}
模拟过程以及指针回溯需要好好理一下,其余的比较简单。
459.重复的子字符串
"SS"找"S"法:
public class Solution {
public bool RepeatedSubstringPattern(string s) {
string ss="";
ss+=s;
ss+=s;
string cpr="";
char[]cc=ss.ToCharArray();
for(int i=1;i<cc.Length-1;i++)
{
cpr+=cc[i];
}
return cpr.Contains(s);
}
}
方法很妙,将需要查找的字符串S后面再拼上一个字符串S,组成"SS",然后掐头去尾两个元素,将剩下的部分用去匹配字符串"S",如果含有字符串S则说明有重复子串,否则没有。