题目描述
一个长度为10000的字符串,写一个算法,找出最长的重复子串,如abczzacbca,结果是bc
Trie 树典型应用。-- 后缀树
code
package leetcode;
/**
* 一个长度为10000的字符串,写一个算法,找出最长的重复子串,如abczzacbca,结果是bc
*/
public class LongestCommonSubstring {
public String LCS(String str){
if(str == null || str.length() == 0) return "";
TrieNode root = new TrieNode();
buildSuffixTrie(str,root);
return longestCommonSuffix(root, "");
}
public void buildSuffixTrie(String str, TrieNode root){
if(str == null || str.length() == 0)
return;
for(int i = 0; i < str.length(); i++){
String tmp = str.substring(i);
TrieNode node = root;
for(int j = 0; j < tmp.length(); j++){
int index = tmp.charAt(j) - 'a';
if(node.next[index] == null){
node.next[index] = new TrieNode();
}else {