给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。
示例 1:
输入: “abcabcbb”
输出: 3
解释: 因为无重复字符的最长子串是 “abc”,所以其长度为 3。
思路:记录不重复子字符串的开始和结束位置用start和end表示。
并且使用HashMap记录对应的字母在字符串中的位置,每次移动end,需要判断map.containsKey(s.charAt(end))如果存在map中则是重复的字符,需要更新start
具体代码如下
class Solution {
public int lengthOfLongestSubstring(String s) {
if(s.length()==0){
return 0;
}
int max=0;
int start=0;//记录子字符串开始的位置
HashMap<Character,Integer> map=new HashMap<Character,Integer>();
for(int end=0;end<s.length();end++){
if(map.containsKey(s.charAt(end))){
//map.get(s.charAt(end))+1,+1将start移动到重复字符的下一个位置
start=Math.max(start,map.get(s.charAt(end))+1);
}
//用于存储最近一次重复字符的位置
map.put(s.charAt(end),end);
//每移动一次记录max的值
max=Math.max(max,end-start+1);
}
return max;
}
}
版权声明:本文为weixin_43842753原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。