学习了一个新strstr算法,sunday算法。
好了,sunday算法还真的很好理解,用下面的例子来说明吧:
先来看普通模式匹配:
public class Solution {
public String strStr(String src, String dst) {
if(src == null||dst == null||src.length() < dst.length()){
return null;
}
int i=0;
int pos=-1;
while(i <= src.length()-dst.length()){
int j=0;
for(;j<dst.length();j++){
if(src.charAt(i+j)!=dst.charAt(j)){
break;
}
}
if(j == dst.length()){
return src.substring(i);
}
i++;//只在此处增加了一些判断!
}
return null;
}
}
匹配串:O U R S T R
O N G X S E A R C H
模式串:S E A R C H
这个例子中上面的字符串是待查找字符串,下面的是子串。sunday的思想是这样的:
首先i,j两个指针指示的位置(也就是从头开始匹配),当发现失配的时候就判断子串的后一位在母串的字符(在上面的例子中是'O'字符,方框标记处,记为k)是否在子串中存在?如果存在则将该位置和子串中的该字符对齐,在从头开始匹配。如果不存在就将子串向后移动,和母串k+1处的字符对齐,再进行匹配。重复上面的操作直到找到,或母串被找完结束。
匹配串:O U R S T R O
N
G X S E A R C H
模式串: _ _ _ _ _ _ _ _ S E A R C H
对于上面的例子继续进行,刚才说了失配,并且'O'在子串中不存在,所以子串向后移动,子串的第一个字符和母串的k+1位置的字符对齐,如上图:
匹配串:O U R S T R O N G X S E A
R C H
模式串:_ _ _ _ _ _ _ _ S E A
R
C H
这次比较还是失配,但是这次的k位置的'R'在子串中出现了,这时候一定要将子串中靠后出现的'R'和母串中的'R'对齐如下图:
匹配串:O U R S T R O N G X S E A
R C H
模式串: _ _ _ _ _ _ _ _ _ _ _ S E A
R C H
为什么是
最靠后的一个呢?如果这里用第一个e来和母串中的e对齐,就有可能将中间出现的可匹配字符串空过去。
这次就匹配成功了,若不成功则继续循环上述步骤。
public class Solution {
public String strStr(String src, String dst) {
if(src == null||dst == null||src.length() < dst.length()){
return null;
}
int i=0;
int pos=-1;//pos为失配时,判断src下一个字符是否在dst里,返回其在dst里是倒数第几个字符。
while(i <= src.length()-dst.length()){
int j=0;
for(;j<dst.length();j++){
if(src.charAt(i+j)!=dst.charAt(j)){
break;
}
}
if(j == dst.length()){
return src.substring(i);
}
//普通匹配中为i++;
if(i+dst.length() < src.length()&&(pos=in_dst(src.charAt(i+dst.length()),dst))!=-1){
i+=pos;
}else{
i+=dst.length()+1;
}
//
}
return null;
}
//dst倒数的第几个字符和字符ch匹配
public int in_dst(char c,String dst){
for(int i=dst.length()-1;i>=0;i--){
if(dst.charAt(i) == c){
return dst.length()-i;//返回的不是i,而是倒数第几个结点匹配到了c!!!!!!!!!!most important!!!!
}
}
return -1;
}
}