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:

    1. Input: s = "level"
    2. Output: "l"
    3. 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:

    1. Input: s = "ababab"
    2. Output: "abab"
    3. Explanation: "abab" is the largest prefix which is also suffix. They can overlap in the original string.

    Example 3:

    1. Input: s = "leetcodeleet"
    2. Output: "leet"

    Example 4:

    1. Input: s = "a"
    2. 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),讲解非常清晰。


    代码实现

    1. class Solution {
    2. public String longestPrefix(String s) {
    3. int[] next = new int[s.length()];
    4. int p = 0, i = 1;
    5. while (i < s.length()) {
    6. if (s.charAt(i) == s.charAt(p)) {
    7. next[i++] = ++p;
    8. } else if (p > 0) {
    9. p = next[p - 1];
    10. } else {
    11. next[i++] = 0;
    12. }
    13. }
    14. return s.substring(0, next[s.length() - 1]);
    15. }
    16. }