Implement strStr()

 

题目:

 

Implement strStr().

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

思路:

直接暴力掉了。。

 

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

 

用Rabin-Karp algorithm算法实现(思路完全按算法导论来的,这里就不说了,主要是Python暴力好像AC不了,有一个卡暴力的数据。。):

class Solution(object):
    def strStr(self, haystack, needle):
        """
        :type haystack: str
        :type needle: str
        :rtype: int
        """
        if len(needle) == 0:
            return 0
        n = len(haystack)
        m = len(needle)
        if n < m:
        	return -1
        d = 26
        q = 14983
        p = 0
        t = 0

        h = 1
        for i in range(0, m - 1):
            i += 1
            h = (h * (d % q)) % q
        for i in range(0, m):
            p = (p * d + ord(needle[i]) - ord('a')) % q
            t = (t * d + ord(haystack[i]) - ord('a')) % q
        for i in range(0, n - m + 1):
            if p == t:
                return i
            if i < n - m:
                t = ((t + q - (ord(haystack[i]) - ord('a')) * h) * d + ord(haystack[i + m]) - ord('a')) % q
        return -1

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值