|
| 1 | +package com.fishercoder.solutions; |
| 2 | + |
| 3 | +public class _2156 { |
| 4 | + public static class Solution1 { |
| 5 | + /** |
| 6 | + * Credit: https://leetcode.com/problems/find-substring-with-given-hash-value/discuss/1730100/Java-rolling-hash(back-to-front)/1242659 |
| 7 | + * <p> |
| 8 | + * We start from the right side and compute rolling hash when moving the window of size k towards the left. |
| 9 | + */ |
| 10 | + public String subStrHash(String s, int power, int modulo, int k, int hashValue) { |
| 11 | + long weight = 1; |
| 12 | + for (int j = 0; j < k - 1; j++) { |
| 13 | + // calculate the weight which will be the power to the k-1 |
| 14 | + // this will be used when we start shifting our window of size k to the left from the end of the string |
| 15 | + weight = (weight * power) % modulo; |
| 16 | + } |
| 17 | + /**We'll have to use the above for loop to calculate weight instead of using Math.pow(power, k - 1) which will render wrong results when power and k are big enough.*/ |
| 18 | + |
| 19 | + // initialize the result string to empty string and keep updating it as we start from the end of the string, and we need to find the first substring that has the hashvalue |
| 20 | + String result = ""; |
| 21 | + |
| 22 | + // right bound of the sliding window which starts at the end of the string |
| 23 | + int right = s.length() - 1; |
| 24 | + |
| 25 | + long hash = 0; |
| 26 | + for (int i = s.length() - 1; i >= 0; i--) { |
| 27 | + |
| 28 | + // add the next value of char for the left pointer into the sliding window |
| 29 | + int val = s.charAt(i) - 'a' + 1; |
| 30 | + |
| 31 | + // update the current hash value |
| 32 | + hash = (hash * power % modulo + val) % modulo; |
| 33 | + |
| 34 | + // when window is at size k, we need to check if we find a matching hash value |
| 35 | + // and update the result, and remove the right most char out of the window to prepare for next iteration |
| 36 | + if (right - i + 1 == k) { |
| 37 | + if (hash == hashValue) { |
| 38 | + result = s.substring(i, right + 1); |
| 39 | + } |
| 40 | + hash = (hash + modulo - (s.charAt(right--) - 'a' + 1) * weight % modulo) % modulo; |
| 41 | + } |
| 42 | + } |
| 43 | + |
| 44 | + return result; |
| 45 | + } |
| 46 | + |
| 47 | + } |
| 48 | +} |
0 commit comments