leetcode :Implement strStr()

来源:互联网 发布:淘宝评价投诉入口 编辑:程序博客网 时间:2024/05/21 09:35

Implement strStr().

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

strstr(str1,str2) 函数用于判断字符串str2是否是str1的子串。如果是,则该函数返回str2在str1中首次出现的地址;否则,返回NULL。

其实在java中就相当于实现indexOf(String str)  函数

那其实最作弊的方法就是下面的了

public class Solution {    public int strStr(String haystack, String needle)     {      return haystack.indexOf(needle);    }}

不过我们本着要好好练习的态度 就换种方法吧

稍微作弊以下   运用substring()来判断是否是字串

public class Solution {    public int strStr(String haystack, String needle)     {        int length=needle.length();        if(length==0)            return 0;        int n=haystack.length();        for(int i=0;i<=n-length;i++)        {            if(haystack.substring(i,i+length).equals(needle))                return i;        }        return -1;    }}
再换一种方法呢   蛮力解决

public class Solution {    public int strStr(String haystack, String needle)     {        if(needle.length()==0)            return 0;        int n=haystack.length();        int i,j;        for(i=0;i<=n-needle.length();i++)        {            for(j=0;j<needle.length();j++)            {                if(haystack.charAt(i+j)!=needle.charAt(j))                {                    break;                }            }            if(j==needle.length())                return i;        }        return -1;    }}

最后一种  KMP算法  也是我认为最有意义的方法

public class Solution {    public int strStr(String haystack, String needle)     {        if(needle.length()==0)            return 0;        int[] table=createTable(needle);        int k=0,j=0;        for(int i=0;i<=haystack.length()-needle.length();)        {            if(haystack.charAt(i+j)==needle.charAt(k))//其实这里可以使用substring的,更方便            {                j++;                k++;                if(k==needle.length())                    return i;            }            else if(k==0) //匹配不到首字母            {                i++;                continue;            }            else//匹配失败  需要重新开始            {                 i=i+k-table[k-1];  //k-table[k-1]就是部分匹配值                 k=0;                 j=0;            }        }        return -1;    }    public int[] createTable(String needle)    {        int n=needle.length();        int[] table=new int[n];        table[0]=0;        int k=0;        for(int i=1;i<n;i++)        {            if(needle.charAt(i)==needle.charAt(k))            {                k++;                table[i]=k;            }            else            {                table[i]=0;                k=0;            }                    }        return table;    }}




0 0
原创粉丝点击