1392. Longest Happy Prefix
https://leetcode.com/problems/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.
Example 1:
Example 2:
Example 3:
Example 4:
Constraints:
1 <= s.length <= 10^5
s
contains only lowercase English letters.
对给定str找最长匹配的前后缀,前后缀之间可以有重叠。前后缀匹配=> KMP。KMP本质可看作是dp,dp[i]存以pattern字符串A中以i为底可匹配的最长前后缀长度。ptr初始为dp[i -1],当A[i]和dp[ptr]不等时,ptr = dp[ptr],直到相等或ptr == 0。比如aacaad的dp = [0,1,0,1,2,0],匹配d时先检查d和c是否相等,对应aac和aad;不等时往前跳到下一个与A[i-1]匹配的位置,匹配a和d,对应aa和ad。过程如下,方块为未知i,△为prefix中下一个和A[i]匹配的字符:
除此之外还可以用rolling hash做,只用O(1)空间,参加lee215的答案。
Last updated
Was this helpful?