LeetCode六月挑战(6.19 )Longest Duplicate Substring LeetCode 1044
Given a string S
, consider all duplicated substrings: (contiguous) substrings of S that occur 2 or more times. (The occurrences may overlap.)
Return any duplicated substring that has the longest possible length. (If S
does not have a duplicated substring, the answer is ""
.)
Example 1:
1 | Input: "banana" |
Example 2:
1 | Input: "abcd" |
Note:
2 <= S.length <= 10^5
S
consists of lowercase English letters.
思路
二分答案,得到长度以后,判断字符串是否相同,采用Robin-Karp算法,计算不同长度的字符串对应的哈希值。
1
2
3
4
5
6
7
8e.g.
s = banana;
//将每个字符转换为int类型数组
c(b) = s.charAt(0) -'a';
c(a) = s.charAt(1) - 'a';
c(n) = s.charAt(2) - 'a';
hash(bana) = c(b)*26^3+c(a)*26^2+c(n)*26^1+c(a)*26^0;
hash(anan) = (hash(bana) - c(b)*26^3)*26 + c(n)*26^0;
代码
java
1 | class Solution { |