两个字符串的匹配,最合适的方法自然是KMP算法。KMP有点忘了, 这里先放一个简单的遍历的方法。 过段时间要补上KMP的解法
public class Solution {
public String strStr(String haystack, String needle) {
int l1 = haystack.length();
int l2 = needle.length();
if( l1 < l2 )
{
return null;
}
if( l2 == 0 )
{
return haystack;
}
for( int i=0;i<l1-l2+1;++i )
{
if( haystack.charAt(i) == needle.charAt(0) )
{
int st=1;
while( st<l2 )
{
if( haystack.charAt(i+st) != needle.charAt(st) )
{
break;
}
++st;
}
if( st == l2 )
{
return haystack.substring(i);
}
}
}
return null;
}
}
KMP算法用的不多,还是会忘记。 大体重温了一遍思想,这个还需要记忆和使用啊
public class Solution {
int next[] = new int[100001];
public String strStr(String haystack, String needle) {
int l1 = haystack.length();
int l2 = needle.length();
if( l1 < l2 )
{
return null;
}
if( l2 == 0 )
{
return haystack;
}
getNext(needle);
int i,j;
i=0;
j=0;
while( i<l1 )
{
if( j == -1||haystack.charAt(i)==needle.charAt(j) )
{
i++;
j++;
}
else
{
j = next[j];
}
if( j == l2 )
{
return haystack.substring(i-l2);
}
}
return null;
}
void getNext(String p)
{
int j,k;
next[0]=-1;
j=0;
k=-1;
while(j<p.length()-1)
{
if(k==-1||p.charAt(j)==p.charAt(k))
{
j++;
k++;
next[j]=k;
}
else
k=next[k];
}
}
}