在 JavaScript中。如果您包含重叠字符串,您实际上可以拥有超过原始长度一半的最大重复子字符串:字符串“abababababab4”在索引 0 和 2 处具有字符串“ababababab”
// For some fancy printing
function post(string) {
document.getElementById("stati").innerHTML += string;
}
var myarray = ['b','r','o','w','n',
'f','o','x',
'h','u','n','t','e','r',
'n','f','o','x',
'r','y','h','u','n'];
var string = myarray.join("");
var longestRepeated = "";
// i = current size of substring
// i loop runs string.length times;
// looks for large repeated substrings first
for (i = string.length; i > 0; i--) {
post("<code>Searching all substrings of length " + i + "</code><br>");
// j = current beginning index of substring
// j loop runs (string.length - substring.length + 1) times;
// checks for repeat of subStr in
// range (indexOf(subStr), whileCurrentSizeiStillFitsInString]
for (j = 0; j < string.length - i; j++) {
var subStr = string.substring(j, j + i);
post("<code class='a'>at index " + j + ", substring = '" +
subStr + "'</code><br>");
// if subStr is matched between indexOf(subStr) + 1 and
// the end of the string, we're done here
// (I'm not checking for multiple repeated substrings
// of the same length. Get over it.)
if (string.indexOf(subStr, j + 1) != -1) {
longestRepeated = subStr;
break;
}
}
if (longestRepeated.length) break;
}
if (longestRepeated.length) alert("Longest repeated substring: " +
subStr);
else alert("Longest repeated substring is the whole string.");