分析匹配串的子串与子串的子串之间的关系,例如aabcbcaab(长度为9)
其子串abcbcaab的前缀子串:
a,ab,abc,abcb,abcbc,abcbca,abcbcaa,abcbcaab//
另一类子串2:
a、aa,aab,aabc,aabcb,aabcbc,aabcbca,aabcbcaa,aabcbcaab//是做为匹配串的开头
还有一类子串3:
aabcbcaab, abcbcaab, bcbcaab, cbcaab, bcaab, caab, aab, ab, b,//是作为匹配串的结尾
假定子串2中的某个是已匹配的串,那么
从最长的匹配串尾开始将他和匹配串头子串匹配,没匹配上,依次换比它小的匹配串来匹配。如果匹配上,那回退量为已匹配串的长度减匹配串尾;
实现:
子串1:
String str1[]=new String(i);
for(int i=0;i<needle.length;i++)
{str1[i]=strcat(needle,1,i);}
子串2:
Sring str2[]=new String(i);
for(int i=0;i<needle.length;i++)
{str2[i]=strcat(needle,0,i);}
子串3:
String str3[]=new String(i);
for(int i=needle.length,i>=0;i--)
{str3[i]=strcat(needle,i,nedle.length);}
回退量:
int [] back(String needle){
int k =0//记录为匹配串开头的子串与为匹配串结尾的子串匹配时最佳匹配串的位置
int l[]=new Int(needle.length);
for(int i;i<needle.length;i++) l[i]=0;
for(int i;i<needle.length;i++)
for(int j=i;j<i;j++)
{
{
if(strcmp(str2[i]==str3[j])) k=j+1;
}
l[i]=k;
}
return I;
}
strStr()函数实现:
int strStr(String haystack,String needle){
if(hayStack.length==0) return 0;
if (needle.length==0) return 0;
if(needle.length>haystack.length) return -1;
int[] backNumber=new Int(needle.length);
backNumber=back(needle);
int j=0;int b=0;//b 用于记录回退量
for (int i=0;i<haystack.length;i++)
{
if(strcmp(needle[j],haystack[i])==0) j++;
else if(j==0) ;
else if(j>needle.length) return i-j+1;
else{
i=i-backNumber[j-1]-1;
j=backNumber;
}
}
return -1;
}