LC1044. Longest Duplicate Substring

https://leetcode.com/problems/longest-duplicate-substring/

  • 라빈카프를 쓰는문제.
  • Rolling Hash 를 활용해서 동일 문자열을 찾는 방법이다. 길이가 같을때 유효하게 사용할 수 있다는 것은 확인했다.
  • 백준에도 같은 문제가 있단다. 3033번: 가장 긴 문자열, 다행히 같은 풀이로 풀린다.
  • unordered_multimap을 쓰지말고 linked-list hash vector를 쓰면 더 빠르게 풀린다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
class Solution {
public:
    const long long KNUTH = 2654435769;
    const long long POW = 29;
    vector<long long> pow;
    string ans = "";
    
    bool check(string& S, int m) {
        if(m==0) return false;
        unordered_multimap<int, int> table;
        long long hash = 0;
        for(int i = 0; i < m; i++)
            hash = (hash + S[i]*pow[m-1-i])%KNUTH;
        table.insert({(int)hash, 0});
        for(int i = 1; i + m <= S.size(); i++) {
            hash = (hash - S[i-1]*pow[m-1]%KNUTH + KNUTH)*POW%KNUTH;
            hash = (hash + S[i+m-1])%KNUTH;
            
            if(!table.count(hash))
                table.insert({(int)hash, i});
            else {
                const auto [lb, ub] = table.equal_range(hash);
                for(auto it = lb; it != ub; it++) {
                    if(S.substr(it->second,m) == S.substr(i, m)) {
                        if(ans.size() < m)
                            ans = S.substr(i, m);
                        return true;
                    }
                }
            }
        }
        return false;
    }
           
    string longestDupSubstring(string S) {
        pow = {1, POW};
        for(int i = 2; i <= S.size(); i++)
            pow.push_back(pow.back()*POW%KNUTH);
        int lo = 0, hi = S.size();
        while(lo < hi) {
            int mid = (lo + hi)/2;
            if(!check(S, mid)) hi = mid;
            else lo = mid+1;
        }
        return ans;
    }
};