力扣网解题(三 无重复字符的最长子串)
原题描述:
解题代码:
public class LongestSubstringWithoutRepeatingCharacters {
public static int lengthOfLongestSubstring(String s) {
int i = 0;
int step = 0;
Map<Character,Integer> con = new HashMap<>(16);
StringBuilder str = new StringBuilder();
StringBuilder tempStr = new StringBuilder();
while ( i < s.length()){
if(con.get(s.charAt(i)) != null){
con.clear();
if(tempStr.length() > str.length()){
str = tempStr;
}
tempStr = new StringBuilder();
step ++;
i = step;
}else{
tempStr.append(s.charAt(i));
con.put(s.charAt(i),i);
i++;
}
}
if(tempStr.length() > str.length()){
str = tempStr;
}
return str.length();
}
public static int lengthOfLongestSubstring2(String s) {
Map<Character,Integer> con = new HashMap<>(16);
StringBuilder res = new StringBuilder();
StringBuilder str = new StringBuilder();
int i = 0;
while ( i < s.length()){
char b = s.charAt(i);
if(con.get(b) != null){
if(res.length() < str.length()){
res = str;
}
str = new StringBuilder(str.substring(1 + str.toString().indexOf(b)));
}else{
con.put(b,i);
}
str.append(b);
i++;
}
if(res.length() < str.length()){
res = str;
}
return res.length();
}
public static void main(String[] args) {
String s = " ";
System.out.println(lengthOfLongestSubstring2(s));
}
}