1392. Longest Happy Prefix (H)

Longest Happy Prefix (H)

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.

Example 3:

Input: s = "leetcodeleet"
Output: "leet"

Example 4:

Input: s = "a"
Output: ""

Constraints:

  • 1 <= s.length <= 10^5
  • s contains only lowercase English letters.

题意

找到字符串s中最长的非空前缀子串,使其同时也是s的后缀子串(不能是s本身)。

思路

寻找最大公共前后缀问题,实际就是去生成KMP的next数组。

关于KMP算法,推荐视频Knuth–Morris–Pratt(KMP) Pattern Matching(Substring search),讲解非常清晰。


代码实现

class Solution {
    public String longestPrefix(String s) {
        int[] next = new int[s.length()];
        int p = 0, i = 1;
        
        while (i < s.length()) {
            if (s.charAt(i) == s.charAt(p)) {
                next[i++] = ++p;
            } else if (p > 0) {
                p = next[p - 1];
            } else {
                next[i++] = 0;
            }
        }
        
        return s.substring(0, next[s.length() - 1]);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值