题目:最长不含重复字符的子字符串
思路: 遍历字符串,把字符加入到hashmap中,key存字符,value存下标;如果出现重复的字符,那就求开头下标到此value之间的长度,则下次开头的下标就是重复的字符对应的下标+1;
class Solution {
public int lengthOfLongestSubstring(String s) {
HashMap<Character, Integer> map = new HashMap<>();
char[] c = s.toCharArray();
int maxlen = 0;
int startKeyIndex = 0;
for (int i = 0; i < c.length; i++) {
if (map.containsKey(c[i]) && map.get(c[i]) >= startKeyIndex) {
int templen = i - startKeyIndex;
if (templen > maxlen)
maxlen = templen;
startKeyIndex = map.get(c[i]) + 1;
map.put(c[i], i);
}
map.put(c[i], i);
}
if (maxlen < (c.length-startKeyIndex)){
maxlen = c.length-startKeyIndex;
}
return maxlen;
}
}