1392. Longest Happy Prefix
Description
A string is called a happy prefix if is a non-empty prefix which is also a suffix (excluding itself).
Given a string s
, return the longest happy prefix of s
. Return an empty string ""
if no such prefix exists.
Example 1:
Input: s = "level" Output: "l" Explanation: s contains 4 prefix excluding itself ("l", "le", "lev", "leve"), and suffix ("l", "el", "vel", "evel"). The largest prefix which is also suffix is given by "l".
Example 2:
Input: s = "ababab" Output: "abab" Explanation: "abab" is the largest prefix which is also suffix. They can overlap in the original string.
Constraints:
1 <= s.length <= 105
s
contains only lowercase English letters.
Solutions
Solution: Longest Prefix Suffix
- Time complexity: O(n)
- Space complexity: O(n)
JavaScript
js
/**
* @param {string} s
* @return {string}
*/
const longestPrefix = function (s) {
const n = s.length;
const lps = Array.from({ length: n }, () => 0);
let length = 0;
for (let index = 1; index < n; index++) {
while (length && s[index] !== s[length]) {
length = lps[length - 1];
}
if (s[index] === s[length]) {
length += 1;
}
lps[index] = length;
}
return s.slice(0, lps[n - 1]);
};