原题链接:力扣
描述:
给定一个字符串 s
,请你找出其中不含有重复字符的 最长子串 的长度
输入: s = "abcabcbb"
输出: 3
解释: 因为无重复字符的最长子串是 "abc",所以其
长度为 3。
解题思路:
把s转换为char[]类型,然后创建一个map,key为对应的char,value为char对应的index位置。
从左向后遍历,记录start和end。首先去map中查找有没有重复,如果没有,则start不变,end++,maxLength+1,并且把当前字符加入到map当中。
如果有重复,则获取当前字符位置,把map中star到index中所有字符串清空。然后start=index+1,加入到map中继续遍历。
举个例子eabcafdb。
e,a,b,c依次加入到map中,这时候maxLength=4,
读到第4位a时,start=0,index=1,则清掉map中e和a的记录。start改为index+1=2;(从0开始计算)
代码:
class Solution {
public int lengthOfLongestSubstring(String s) {
int start = 0;
int end = 0;
int maxLength = 0;
char[] chars = s.toCharArray();
HashMap<Integer, Integer> timeMap = new HashMap<>();
while (end < chars.length) {
int aChar = chars[end];
Integer index = timeMap.get(aChar);
if (index == null) {
timeMap.put(aChar, end);
end++;
if ((end - start) > maxLength) {
maxLength = end - start;
}
continue;
}
for (int i = start; i < index; i++) {
timeMap.remove((int) chars[i]);
}
start = index + 1;
timeMap.put(aChar, end);
end++;
}
return maxLength;
}
}