LeetCode--28. Implement strStr()

        这个是个easy的题目,首先想到直接用String.indexOf()方法直接求,但觉得很耻辱!!!于是有了如下思路:遍历整个文本串(长度为m),比对文本串字母与目标串(长度为n)首字母是否相同,如果相同就检查模式串后面的字母是否相同,但是越简单的题目越容易有小bug,尤其这里面两个循环里的的break处理的有点大意了。这个思路非常普通,时间复杂度O(mn)。KMP算法应该是最优的结果。

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

猜你喜欢

转载自blog.csdn.net/To_be_to_thought/article/details/84679263