28. Implement strStr()(String字符串匹配)

来源:互联网 发布:淘宝店铺首页链接在哪 编辑:程序博客网 时间:2024/05/21 10:01

题目:

Implement strStr().

Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

Subscribe to see which companies asked this question

字符串匹配算法:

算法一:Brute Force(BF或蛮力搜索) 算法

时间复杂度O(MN)

模式串从左往右与匹配串比较,匹配失败,模式串向右移动一位,直到匹配到为止。效率低下,思想简单,就不贴代码了。

算法二:KMP算法

利用不匹配字符的前面那一段字符的最长前后缀来尽可能地跳过最大的距离,需要计算模式串的跳转表next[]。如果在匹配过程中,在字符j时匹配失败,就移动模式串的next[j]到当前字符,继续匹配。

在计算模式串的next[]跳转表时,引入一个概念f(j),其含义是,对于模式串的第j个字符pattern[j],f(j)是所有满足使pattern[1...k-1] = pattern[j-(k-1)...j - 1](k < j)成立的k的最大值。

下面给出根据f(j)值求next[j]的递推公式:

如果 pattern[j] != pattern[f(j)],next[j] = f(j);

如果 pattern[j] = pattern[f(j)],next[j] = next[f(j)];

代码:

public class Solution {public int[] next;    public int strStr(String haystack, String needle) {    if(needle.isEmpty())return 0;    if(haystack.isEmpty())return -1;        next = new int[needle.length()+1];        getNext(needle);        int j=0,i=0;        while(i<haystack.length())        {        while(j>=0 && haystack.charAt(i)!=needle.charAt(j))j=next[j+1]-1;        j++;        i++;        if(j==needle.length())return i-j;        }        return -1;    }        public void getNext(String str)    {    //next从1开始    int i=1,f=0;    while(i<str.length())    {    //找到满足pattern[k] = pattern[j]的最大k值。    while(f>0 && str.charAt(i-1)!=str.charAt(f-1))    {    f=next[f];    }    i++;    f++;    if(str.charAt(i-1)==str.charAt(f-1))    {    next[i]=next[f];    }    else    {    next[i]=f;    }    }    }}
算法三:BM(Boyer-Moore)算法 


算法四:Sunday算法

如果匹配失败,则查找目标串中,与模式串对齐最后一个字符的后面一个字符ch,并查找模式串中等于ch的字符,使之与目标串的ch对齐。

public class Solution {public int strStr(String haystack, String needle) {    if(needle.isEmpty())return 0;    if(haystack.isEmpty())return -1;int[] dic = new int[26];for(int i=0;i<26;i++){dic[i]=needle.length()+1;}for(int i=0;i<needle.length();i++){//设置每个字符离needle尾字符的长度加一dic[needle.charAt(i)-'a']=needle.length()-i;}//目标字符串与模式串对其位置int pos=0;   int i,j;while(pos<haystack.length()-needle.length()+1){i=pos;for(j=0;j<needle.length();++j,++i){if(haystack.charAt(i)!=needle.charAt(j)){//查找目标串中,与模式串对齐最后一个字符的后面那个字符ch,//并查找模式串中等于ch的字符,使之与目标串的ch对齐if(pos+needle.length()<haystack.length()-needle.length()+1)pos+=dic[haystack.charAt(pos+needle.length())-'a'];else pos++;break;}}if(j==needle.length())return pos;}return -1;}}


参考文献:http://blog.csdn.net/joylnwang/article/details/6778316/

http://blog.163.com/yangfan876@126/blog/static/80612456201342205056344/

0 0
原创粉丝点击