一开始自己想的太简单了,于是就2了,那个注释的代码如何处理“dvdf”这样的字符串?
好吧,于是找到了一种精妙的解法,用hashmap,
精妙在
i = map.get(chars[i]);
map.clear();
好好体会,这也就罢了。但是自己接下来犯得那两个错误,是不是有些太跌份了!!是不是这两天set用多了,搞混了?????
public class Solution {
public int lengthOfLongestSubstring(String s) {
if (s == null || s.length() < 1) {
return 0;
}
char[] chars = s.toCharArray();
int prevMax = 0;
Map<Character/*char of chars*/, Integer/*index of chars*/> map = new HashMap<>();
for (int i = 0; i < s.length(); i++) {
//if (map.contains(chars[i])) {
if (map.containsKey(chars[i])) {
prevMax = Math.max(prevMax, map.size());
i = map.get(chars[i]);
map.clear();
} else {
//map.add(chars[i], i);
map.put(chars[i], i);
}
}
return Math.max(prevMax, map.size());
// wrong
// if (s == null || s.length() < 1) {
// return 0;
// }
// int maxL = 0;
// Set<Character> set = new HashSet<>();
// for (int i = 0; i < s.length(); i++) {
// if (set.add(s.charAt(i))) {
// } else {
// maxL = Math.max(maxL, set.size());
// set = new HashSet<>();
// set.add(s.charAt(i));
// }
// }
// //return maxL;
// return Math.max(maxL, set.size());
}
}