leetcode :Implement strStr()

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值