作者:disappearedgod
时间:2014-8-26
题目
Longest Substring Without Repeating Characters
Total Accepted: 20773 Total Submissions: 93405 My SubmissionsGiven a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.
解法
无脑解法,Trie树建树,字符串倒序查找。
public class Solution {
public String longestPalindrome(String s) {
String ret = null;
int max = 0;
if(s.length() < 2)
return s;
TrieST trie = new TrieST();
for(int i = 0; i < s.length(); i++){
trie.put(s.substring(i), s.length()-i);
}
String rs = new StringBuffer(s).reverse().toString();
for(int i = 0; i < rs.length(); i++){
int tmp = trie.get(rs.substring(i));
if(tmp > max){
max = tmp;
ret = rs.substring(i);
}
}
return ret;
}
public class TrieST{
private Node root;
private int R = 256;
private class Node{
private int val;
private Node[] next = new Node[R];
}
public int get(String key){
Node x = get(root, key, 0);
if(x == null)
return 0;
return x.val;
}
private Node get(Node x, String key, int d){
if(x == null) return null;
if(d == key.length()) return x;
char c = key.charAt(d);
return get(x.next[c], key, d+1);
}
public void put(String key, int val){
root = put(root, key, val, 0);
}
private Node put(Node x, String key, int val, int d){
if(x == null) return null;
if(d == key.length()){
x.val = val;
return x;
}
char c = key.charAt(d);
x.next[c] = put(x.next[c], key, val, d+1);
return x;
}
}
}