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.

[分析] 经典的字符查找问题,有四种经典解法, 暴力法,hash法,Boyer-Moorer算法和KMP算法。leetcode上分析指出面试时写出暴力法即可,关键是暴力法代码要写得clean。 实现1采用two pointer 方式,代码上不如实现1.1 clean。两者算法复杂度均为O(n * m)。 实现2 是一种个人认为最容易理解的O(n)算法,叫rolling hash算法,基本思想是利用一个hashcode表示一个字符串,对比长度等于代匹配串的子串的hash是否和待匹配串的hash值相等来查找,为防止溢出使用long表示hashcode。

[ref]
http://www.ruanyifeng.com/blog/2013/05/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm.html
http://blog.csdn.net/kenden23/article/details/17029625


[code="java"]// Method 2: rolling hash, O(m + n - m)
    public int strStr(String haystack, String needle) {
        if (haystack == null || needle == null || haystack.length()  right)
                    return i;
                else
                    i++;
            }
            return -1;
        } else {
            return -1;
        }
    }

猜你喜欢

转载自likesky3.iteye.com/blog/2219474
今日推荐