Given 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.
public class LongestSubstringWithoutRepeatingchar2 {
public static void main(String[] args) {
String str = "abcabcbd";
// String str = "";
int i = -1;
int j = -1;
Map<Character, Integer> map = new HashMap<>();
int len = 0;
while (true){
boolean f1 = false, f2 = false;
while (i<str.length()-1) {
f1 = true;
i++;
char ch = str.charAt(i);
if (map.containsKey(ch)) {
map.put(ch, map.get(ch) + 1);
break;
} else {
map.put(ch, 1);
len = Math.max(len, i - j);
}
}
while (j<i){
f2 = true;
j++;
char ch = str.charAt(j);
Integer val = map.get(ch);
if(val>=2){
map.put(ch,map.get(ch)-1);
len = Math.max(len,i-j);
break;
}else{
map.remove(ch);
}
}
if(!f1 && !f2){
break;
}
}
System.out.println(len);
// System.out.println(len);
}
}
No comments:
Post a Comment