记录一下自己解题时踩过的坑和AC的代码。
这道题求最长不含重复字符的子串的长度。
想法:
从左到右遍历字符串,用一个变量start保存当前最长子串的起始下标,用一个map保存当前所遍历到的字符和字符最新出现的下标。当出现重复的字符时,求子串的长度,并更strat变量和新重复字符在map中存储重复字符的下标。
没有考虑到的点:
1、更新start变量时,最初想的是用重复字符的下标+1。这样就没有考虑到重复字符的下表可能比start小的情况。start只能往大了更新,不能变小。
2、写代码的时候没有考虑到最后一个字符是之前没有出现过的字符的情况下,计算子串的长度时应该把这个字符也考虑进去。
AC代码如下(代码写的可能不够高效、简洁,欢迎拍砖):
class Solution {
public int lengthOfLongestSubstring(String s) {
int start = 0;
int length = 0;
Map<Character,Integer> indexMap = new HashMap<Character, Integer>();
char [] chars = s.toCharArray();
if (chars.length>0) {
int i;
for (i = 0; i < chars.length; i++) {
if (!indexMap.containsKey(chars[i])) {
if(i == chars.length-1) {
int tempLen = i - start + 1 ;
length = length > tempLen ? length : tempLen;
}
indexMap.put(chars[i], i);
} else {
int repeatIndex = indexMap.get(chars[i]);
int tempLen = 0;
if (repeatIndex < start){
tempLen = i - start + 1;
length = length > tempLen ? length : tempLen;
}
else {
tempLen = i - start;
length = length > tempLen ? length : tempLen;
start = indexMap.get(chars[i]) + 1;
}
indexMap.put(chars[i], i);
}
}
}
return length;
}
}