Skip to content

Commit ca534db

Browse files
committed
Add solution #1392
1 parent 7396866 commit ca534db

File tree

2 files changed

+34
-1
lines changed

2 files changed

+34
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# 1,275 LeetCode solutions in JavaScript
1+
# 1,276 LeetCode solutions in JavaScript
22

33
[https://leetcodejavascript.com](https://leetcodejavascript.com)
44

@@ -1062,6 +1062,7 @@
10621062
1389|[Create Target Array in the Given Order](./solutions/1389-create-target-array-in-the-given-order.js)|Easy|
10631063
1390|[Four Divisors](./solutions/1390-four-divisors.js)|Medium|
10641064
1391|[Check if There is a Valid Path in a Grid](./solutions/1391-check-if-there-is-a-valid-path-in-a-grid.js)|Medium|
1065+
1392|[Longest Happy Prefix](./solutions/1392-longest-happy-prefix.js)|Hard|
10651066
1400|[Construct K Palindrome Strings](./solutions/1400-construct-k-palindrome-strings.js)|Medium|
10661067
1402|[Reducing Dishes](./solutions/1402-reducing-dishes.js)|Hard|
10671068
1408|[String Matching in an Array](./solutions/1408-string-matching-in-an-array.js)|Easy|
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
/**
2+
* 1392. Longest Happy Prefix
3+
* https://leetcode.com/problems/longest-happy-prefix/
4+
* Difficulty: Hard
5+
*
6+
* A string is called a happy prefix if is a non-empty prefix which is also a suffix
7+
* (excluding itself).
8+
*
9+
* Given a string s, return the longest happy prefix of s. Return an empty string ""
10+
* if no such prefix exists.
11+
*/
12+
13+
/**
14+
* @param {string} s
15+
* @return {string}
16+
*/
17+
var longestPrefix = function(s) {
18+
let prefixLength = 0;
19+
const prefixHash = new Array(s.length).fill(0);
20+
21+
for (let i = 1; i < s.length; i++) {
22+
while (prefixLength > 0 && s[i] !== s[prefixLength]) {
23+
prefixLength = prefixHash[prefixLength - 1];
24+
}
25+
if (s[i] === s[prefixLength]) {
26+
prefixLength++;
27+
}
28+
prefixHash[i] = prefixLength;
29+
}
30+
31+
return s.slice(0, prefixHash[s.length - 1]);
32+
};

0 commit comments

Comments
 (0)