题目描述
输入一个字符串(只包含 a~z 的字符),求其最长不含重复字符的子字符串的长度。例如对于 arabcacfr,最长不含重复字符的子字符串为 acfr,长度为 4。
思路:滑动数组
链接:https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/solution/hua-dong-chuang-kou-by-powcai/
class Solution {
public int lengthOfLongestSubstring(String s) {
if(s == null || s.length() == 0){
return 0;
}
HashMap<Character , Integer> map = new HashMap<Character , Integer>();
int max = 0;
for(int start = 0 , end = 0 ; end < s.length() ; end++){
if(map.containsKey(s.charAt(end))){
start = Math.max(start , map.get(s.charAt(end)) + 1);
}
max = Math.max(max , end - start + 1);
map.put(s.charAt(end) , end );
}
return max;
}
}