leetcode: Implement strStr()

两个字符串的匹配,最合适的方法自然是KMP算法。KMP有点忘了, 这里先放一个简单的遍历的方法。  过段时间要补上KMP的解法


public class Solution {
    public String strStr(String haystack, String needle) {
        int l1 = haystack.length();
        int l2 = needle.length();
        if( l1 < l2 )
        {
            return null;
        }
        if( l2 == 0 )
        {
            return haystack;
        }
        for( int i=0;i<l1-l2+1;++i )
        {
            if( haystack.charAt(i) == needle.charAt(0) )
            {
                int st=1;
                while( st<l2 )
                {
                    if( haystack.charAt(i+st) != needle.charAt(st) )
                    {
                        break;
                    }
                    ++st;
                }
                if( st == l2 )
                {
                    return haystack.substring(i);
                }
            }
        }
        return null;
    }
}


KMP算法用的不多,还是会忘记。   大体重温了一遍思想,这个还需要记忆和使用啊

 

public class Solution {
    
    int next[] = new int[100001];
    public String strStr(String haystack, String needle) {
        int l1 = haystack.length();
        int l2 = needle.length();
        if( l1 < l2 )
        {
            return null;
        }
        if( l2 == 0 )
        {
            return haystack;
        }
        getNext(needle);
        int i,j;
        i=0;
        j=0;
        while( i<l1 )
        {
            if( j == -1||haystack.charAt(i)==needle.charAt(j) )
            {
                i++;
                j++;
            }
            else
            {
                j = next[j];
            }
            if( j == l2 )
            {
                return haystack.substring(i-l2);
            }
        }
        return null;
    }
    
    void getNext(String p)
    {
        int j,k;
        next[0]=-1;
        j=0;
        k=-1;
        while(j<p.length()-1)
        {
            if(k==-1||p.charAt(j)==p.charAt(k))    
            {
                j++;
                k++;
                next[j]=k;
            }
            else                   
                k=next[k];
        }
    }
}


 

 


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值