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.
Constraints:
1 <= s.length <= 105
s
contains only lowercase English letters.
class Solution:
def longestPrefix(self, s: str) -> str:
for i in range(1, len(s)):
if s[:-i] == s[i:]:
return s[i:]
return ''
class Solution {
private long[] p;
private long[] h;
public String longestPrefix(String s) {
int base = 131;
int n = s.length();
p = new long[n + 10];
h = new long[n + 10];
p[0] = 1;
for (int i = 0; i < n; ++i) {
p[i + 1] = p[i] * base;
h[i + 1] = h[i] * base + s.charAt(i);
}
for (int l = n - 1; l > 0; --l) {
if (get(1, l) == get(n - l + 1, n)) {
return s.substring(0, l);
}
}
return "";
}
private long get(int l, int r) {
return h[r] - h[l - 1] * p[r - l + 1];
}
}
typedef unsigned long long ULL;
class Solution {
public:
string longestPrefix(string s) {
int base = 131;
int n = s.size();
ULL p[n + 10];
ULL h[n + 10];
p[0] = 1;
h[0] = 0;
for (int i = 0; i < n; ++i) {
p[i + 1] = p[i] * base;
h[i + 1] = h[i] * base + s[i];
}
for (int l = n - 1; l > 0; --l) {
ULL prefix = h[l];
ULL suffix = h[n] - h[n - l] * p[l];
if (prefix == suffix) return s.substr(0, l);
}
return "";
}
};
func longestPrefix(s string) string {
base := 131
n := len(s)
p := make([]int, n+10)
h := make([]int, n+10)
p[0] = 1
for i, c := range s {
p[i+1] = p[i] * base
h[i+1] = h[i]*base + int(c)
}
for l := n - 1; l > 0; l-- {
prefix, suffix := h[l], h[n]-h[n-l]*p[l]
if prefix == suffix {
return s[:l]
}
}
return ""
}
function longestPrefix(s: string): string {
const n = s.length;
for (let i = n - 1; i >= 0; i--) {
if (s.slice(0, i) === s.slice(n - i, n)) {
return s.slice(0, i);
}
}
return '';
}
impl Solution {
pub fn longest_prefix(s: String) -> String {
let n = s.len();
for i in (0..n).rev() {
if s[0..i] == s[n - i..n] {
return s[0..i].to_string();
}
}
String::new()
}
}