File tree 2 files changed +34
-1
lines changed
2 files changed +34
-1
lines changed Original file line number Diff line number Diff line change 1
- # 1,275 LeetCode solutions in JavaScript
1
+ # 1,276 LeetCode solutions in JavaScript
2
2
3
3
[ https://leetcodejavascript.com ] ( https://leetcodejavascript.com )
4
4
1062
1062
1389|[ Create Target Array in the Given Order] ( ./solutions/1389-create-target-array-in-the-given-order.js ) |Easy|
1063
1063
1390|[ Four Divisors] ( ./solutions/1390-four-divisors.js ) |Medium|
1064
1064
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|
1065
1066
1400|[ Construct K Palindrome Strings] ( ./solutions/1400-construct-k-palindrome-strings.js ) |Medium|
1066
1067
1402|[ Reducing Dishes] ( ./solutions/1402-reducing-dishes.js ) |Hard|
1067
1068
1408|[ String Matching in an Array] ( ./solutions/1408-string-matching-in-an-array.js ) |Easy|
Original file line number Diff line number Diff line change
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
+ } ;
You can’t perform that action at this time.
0 commit comments