Java实现:
1 package my;
2
3 import java.util.TreeMap;
4
5 public class Test {
6 //时间复杂度小于等于O(N^2)
7 public void max_unique_substring(String str) {
8 //begin表示最长不重复子串的开始索引
9 int begin = 0;
10 //max_length表示最长不重复子串的长度
11 int max_length = 0;
12 //定义一个容器,用来保存遍历时遇到的每一个字符的出现次数
13 TreeMap<Character,Integer> tm = new TreeMap<>();
14 int n = str.length();
15 int j = 0;
16 int i = 0;
17 while(i<n){
18 //初始化,hash这个数组,用0填充
19 for(int k=0;k<n;k++) {
20 tm.put(str.charAt(k), 0);
21 }
22 tm.put(str.charAt(i), 1);
23 //从i+1开始往后找,遇到和i索引处不一样的元素,就将那个位置的“值”置1
24 //遇到一样的就 break,让j停在现在这个位置
25 for(j=i+1;j<n;j++) {
26 if(tm.get(str.charAt(j))==0)
27 tm.put(str.charAt(j), 1);
28 else
29 break;
30 }
31 //上面j刚好停在了,第一次出现重复的那个位置,相减即为这个时候的最长子串长度
32 //i索引是其的开始
33 if(j-i>max_length) {
34 max_length = j-i;
35 begin = i;
36 }
37 i = j;
38 }
39 System.out.println(max_length + " " + str.substring(begin, begin+max_length)) ;
40 }
41 //测试
42 public static void main(String[] args) {
43 String str1 = "asbf2hcvj4ghs4563ednvhj";
44 Test test = new Test();
45 test.max_unique_substring(str1);
46 }
47
48 }