[LeetCode] Longest Happy Prefix

1392. Longest Happy Prefix

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public:
string longestPrefix(string s) {
vector<int> dp(s.length(), 0);
int j = 0;
for(int i = 1; i < s.length(); i++) {
while(j > 0 and s[i] != s[j]) {
j = dp[j-1];
}
if(s[i] == s[j])
dp[i] = ++j;
}
return s.substr(0,dp.back());
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/18/PS/LeetCode/longest-happy-prefix/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.