lintcode594 - strStr II - hard

Implement strStr function in O(n + m) time.

strStr return the first index of the target string in a source string. The length of the target string is m and the length of the source string is n.

If target does not exist in source, just return -1.

Example

Given source = abcdef, target = bcd, return 1.

Rabin Karp Algorithm。用Hash方程的思想做。自己实现Hash function。

1.提前算好target的code。

2.开始读入source的每个字符,在for循环里计算所有长度为target.length()的子字符串的hashcode。

3.对比,如果code一样,要进一步对比是否substring的确一样以排除false positive.

细节:

1.第二步内比如从abc -> bcd,for循环每次都加了新的字符,d已经被加上去了,你只要轻松地排除窗口刚滑走的a*幂次即可。因为幂次固定是31*target.length(),可以提早把幂次算好。

2.对%BASE这个操作每次计算别忘了。

3.对两个各自对BASE取余过的数做减法后,可能会出来负数,这时候不好

我的实现:

public class Solution {
    /*
     * @param source: A source string
     * @param target: A target string
     * @return: An integer as index
     */
    public int strStr2(String source, String target) {
        // write your code here
        if (source == null || target == null) {
            return -1;
        }
        if (target.length() == 0) {
            return 0;
        }

        int BASE = 100000;
        int length = target.length();

        // 31^length, 31 is HASHBASE.
        int power = 1;
        for (int i = 0; i < length; i++) {
            power = (power * 31) % BASE;
        }

        int targetCode = 0;
        for (int i = 0; i < length; i++) {
            targetCode = (targetCode * 31 + target.charAt(i)) % BASE;
        }

        int sourceCode = 0;
        for (int i = 0; i < source.length(); i++) {
            sourceCode = (sourceCode * 31 + source.charAt(i)) % BASE;

            if (i >= length) {
                //注意这里。可能出现负数的地方不要直接再%,用if处理。
                sourceCode = sourceCode - (source.charAt(i - length) * power) % BASE;
                if (sourceCode < 0) {
                    sourceCode += BASE;
                }
            }

            if (i >= length - 1 && sourceCode == targetCode
                && source.substring(i - length + 1, i + 1).equals(target)) {
                return i - length + 1;
            }
        }

        return -1;
    }
}

九章实现:

public class Solution {
    /**
     * @param source a source string
     * @param target a target string
     * @return an integer as index
     */
    public int strStr2(String source, String target) {
        if(target == null) {
            return -1;
        }
        int m = target.length();
        if(m == 0 && source != null) {
            return 0;
        }

        if(source == null) {
            return -1;
        }
        int n = source.length();
        if(n == 0) {
            return -1;
        }

        // mod could be any big integer
        // just make sure mod * 33 wont exceed max value of int.
        int mod = Integer.MAX_VALUE / 33;
        int hash_target = 0;

        // 33 could be something else like 26 or whatever you want
        for (int i = 0; i < m; ++i) {
            hash_target = (hash_target * 33 + target.charAt(i) - ‘a‘) % mod;
            if (hash_target < 0) {
                hash_target += mod;
            }
        }

        int m33 = 1;
        for (int i = 0; i < m - 1; ++i) {
            m33 = m33 * 33 % mod;
        }

        int value = 0;
        for (int i = 0; i < n; ++i) {
            if (i >= m) {
                value = (value - m33 * (source.charAt(i - m) - ‘a‘)) % mod;
            }

            value = (value * 33 + source.charAt(i) - ‘a‘) % mod;
            if (value < 0) {
                value += mod;
            }

            if (i >= m - 1 && value == hash_target) {
                // you have to double check by directly compare the string
                if (target.equals(source.substring(i - m + 1, i + 1))) {
                    return i - m + 1;
                }
            }
        }
        return -1;
    }
}

原文地址:https://www.cnblogs.com/jasminemzy/p/9429780.html

时间: 2024-08-14 01:39:13

lintcode594 - strStr II - hard的相关文章

[LeetCode] 349 Intersection of Two Arrays &amp; 350 Intersection of Two Arrays II

这两道题都是求两个数组之间的重复元素,因此把它们放在一起. 原题地址: 349 Intersection of Two Arrays :https://leetcode.com/problems/intersection-of-two-arrays/description/ 350 Intersection of Two Arrays II:https://leetcode.com/problems/intersection-of-two-arrays-ii/description/ 题目&解法

使用华邦的SPI FLASH作为EPCS时固化NIOS II软件报错及解决方案

Altera器件有EPCS系列配置器件,其实,这些配置器件就是我们平时通用的SPIFlash,据AlteraFAE描述:"EPCS器件也是选用某家公司的SPIFlash,只是中间经过Altera公司的严格测试,所以稳定性及耐用性都超过通用的SPIFlash".就本人看来,半导体的稳定性问题绝大部分都是由本身设计缺陷造成的,而成熟的制造工艺不会造成产品的不稳定:并且,现在Altera的器件在读入配置数据发生错误时,可以重新读取SPIFlash里面的数据,所以在工艺的稳定性以及设计的可靠性

hdu 1207 汉诺塔II (DP+递推)

汉诺塔II Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 4529    Accepted Submission(s): 2231 Problem Description 经典的汉诺塔问题经常作为一个递归的经典例题存在.可能有人并不知道汉诺塔问题的典故.汉诺塔来源于印度传说的一个故事,上帝创造世界时作了三根金刚石柱子,在一根柱子上从下往

AC日记——小A和uim之大逃离 II 洛谷七月月赛

小A和uim之大逃离 II 思路: spfa: 代码: #include <bits/stdc++.h> using namespace std; #define INF 0x3f3f3f3f struct NodeType { int x,y,k; NodeType(int x_,int y_,int k_):x(x_),y(y_),k(k_){} NodeType(){} }; const int dx[5]={0,-1,0,1,0}; const int dy[5]={0,0,1,0,-

remove-duplicates-from-sorted-list I&amp;II——去除链表中重复项

I.Given a sorted linked list, delete all duplicates such that each element appear only once. For example,Given1->1->2, return1->2.Given1->1->2->3->3, return1->2->3. PS:遍历,而后记录pre,并删除后续重复node 1 /** 2 * Definition for singly-linke

LeetCode 28. Implement strStr()

https://leetcode.com/problems/implement-strstr/ Implement strStr(). Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. 字符串简单题.一定要写的没BUG. 如果不在函数最后一行写return语句的话,LeetCode会出RUNTIME ERROR. Line 27: co

Intersection of Two Arrays I &amp; II

题目链接:https://leetcode.com/problems/intersection-of-two-arrays/ 题目大意:要求两个数组的交集(注意集合是不能含有重复的元素的) 方法1) 先对两个数组进行排序,设置两个指针pA和pB,分别指向这两个数组,比较nums1[pA]和nums[pB] a. 如果想等,则为交集中的元素,++pA, ++pB b. 如果nums[pA] < nums[pB],则++pA c. 否则,++pB 注意数组中有重复的元素(实现代码中的小trick)

Wiggle Sort II

Wiggle Sort II Given an unsorted array nums, reorder it such that nums[0] < nums[1] > nums[2] < nums[3].... 注意事项 You may assume all input has valid answer. 样例 Given nums = [1, 5, 1, 1, 6, 4], one possible answer is [1, 4, 1, 5, 1, 6]. Given nums

Implement strStr()

package cn.edu.xidian.sselab.string; /** *  * @author zhiyong wang * title: Implement strStr() * content: *  Implement strStr(). *   *  Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.  * */pub