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.
题目分析:该题难度不大,有两点需注意。
1.使用map的时候注意应用键值对翻转,key存char数组里的值 value存数组的下标
2、要注意当出现重复字母时,再一次检查直接从重复的那个字母的后一位开始对比。
代码:
public class Solution {
public int lengthOfLongestSubstring(String s) {
char[] ch = s.toCharArray();
int max = 0;
int last;
K: for (int i = 0; i < ch.length;) {
Map<Character, Integer> map = new HashMap<Character, Integer>();
for (int j = i; j < ch.length; j++) {
if (map.containsKey(ch[j])) {
last = j - i;
if (last > max) {
max = last;
}
if (max == 95) {
break K;
}
i = map.get(ch[j]) + 1;
break;
} else {
last = j - i + 1;
map.put(ch[j], j);
if (last > max) {
max = last;
}
}
if (j == ch.length - 1) {
break K;
}
}
}
return max;
}
}