思路一:先找出一个字符串中所有子串,再找出所有子串中最长的那一个;
思路二:每次找出的子串长度都比上一次的子串长,则最后的子串即是最长子串的长度数。
我选择的是第二种方法。
public class FindSubstringMaxlengthNoduplicate {
public static void main(String[] args) {
String s = "adcdghcwioizhfksjdyuiodfhjskhgkhgeisdcjdkh";
ArrayList<String> result = findMaxLength(s);
int maxLength = result.get(result.size()-1).length();
System.out.println("最长不重复子串为:");
for(String r : result){
if(r.length() == maxLength){
System.out.println(r);
}
}
}
private static ArrayList<String> findMaxLength(String s) {
int maxLength = 0;
HashSet<Character> hs = null;
ArrayList<String> list = new ArrayList<String>();
for(int j = 0; j < s.length(); ++j){
int count = 0;
hs = new HashSet<Character>();
for(int i = j; i < s.length(); ++i){
if(hs.add(s.charAt(i))){
++count;
if(count == s.length()-j){
if(count >= maxLength){
maxLength = count;
list.add(s.substring(j,i));
}
j = s.length();
}
}else{
if(count >= maxLength){
maxLength = count;
list.add(s.substring(j,i));
}
int numOfDupllicate = 0;
for(int k = j; k < i; ++k){
if(s.charAt(i) != s.charAt(k)){
++numOfDupllicate;
}else{
break;
}
}
j = j+numOfDupllicate;
break;
}
}
}
return list;
}
}