-
Notifications
You must be signed in to change notification settings - Fork 228
/
1044-longest-duplicate-substring.js
88 lines (83 loc) · 1.9 KB
/
1044-longest-duplicate-substring.js
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
/**
* @param {string} s
* @return {string}
*/
const longestDupSubstring = function(s) {
const n = s.length
let l = 0, r = n, res = ''
while(l < r) {
const mid = (l + r + 1) >> 1
const [chk, str] = valid(s, mid)
if(chk) {
l = mid
res = str
} else {
r = mid - 1
}
}
return res
};
function valid(s, len) {
const set = new Set()
for(let i = 0, n = s.length; i <= n - len; i++) {
const tmp = s.substr(i, len)
if(set.has(tmp)) return [true, tmp]
set.add(tmp)
}
return [false, '']
}
// another
/**
* @param {string} S
* @return {string}
*/
const longestDupSubstring = function(S) {
const R = 26,
MOD = 1e9 + 7
let lo = 0,
hi = S.length - 1,
res = ''
while (lo < hi) {
const len = Math.ceil((lo + hi) / 2)
const sub = rabinKarp(S, len)
if (sub !== '') {
lo = len
res = sub
} else {
hi = len - 1
}
}
return res
function rabinKarp(str, len) {
const aCode = ('a').charCodeAt(0)
let RM = 1
// 等价于RM=Math.pow(R,M-1) % MOD
// 由于JS精度问题拆解计算
for (let i = 1; i < len; i++) {
RM = (RM * R) % MOD
}
const map = new Map()
let num = 0
// 计算前len个字符串的散列值
for (let i = 0; i < len; i++) {
const code = str.charCodeAt(i) - aCode
num = (num * R + code) % MOD
}
map.set(num, 0)
// 后续计算散列值
for (let i = 0; i < str.length - len; i++) {
const preCode = str.charCodeAt(i) - aCode,
curCode = str.charCodeAt(i + len) - aCode
num = (num + MOD - ((preCode * RM) % MOD)) % MOD
num = (num * R + curCode) % MOD
if (map.has(num)) {
const sub = str.substring(i + 1, i + 1 + len)
const preId = map.get(num),
preSub = str.substring(preId, preId + len)
if (sub === preSub) return sub
}
map.set(num, i + 1)
}
return ''
}
}