#1392

Longest Happy Prefix

candidate master · 1370 · lc hard +32 · verified · 52% accepted · 1,578 likes · top 42%

Description

A happy prefix of string s is a non-empty prefix that is also a suffix, but not the entire string. Given s, return its longest happy prefix, or an empty string "" if none 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.

Code

1
2
3