Skip to content

Commit c800c61

Browse files
authored
Create 1392-longest-happy-prefix.js
1 parent 05d4977 commit c800c61

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

1392-longest-happy-prefix.js

+29
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/**
2+
* @param {string} s
3+
* @return {string}
4+
*/
5+
const longestPrefix = function(s) {
6+
return s.slice(0, dfa().pop())
7+
function dfa() {
8+
let i = 1
9+
let j = 0
10+
const len = s.length
11+
const prefix = Array(len + 1).fill(0)
12+
while(i < len) {
13+
if(s[j] === s[i]) {
14+
j++
15+
i++
16+
prefix[i] = j
17+
} else {
18+
if(j > 0) j = prefix[j]
19+
else {
20+
i++
21+
prefix[i] = 0
22+
}
23+
}
24+
}
25+
return prefix
26+
}
27+
};
28+
29+

0 commit comments

Comments
 (0)