题目
Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for “abcabcbb” is “abc”, which the length is 3. For “bbbbb” the longest substring is “b”, with the length of 1.
实现
“滑动窗口” 原理:比方说 abcabccc 当你右边扫描到abca的时候你得把第一个a删掉得到bca,然后”窗口”继续向右滑动,每当加到一个新char的时候,左边检查有无重复的char, 然后如果没有重复的就正常添加,有重复的话就左边扔掉一部分(从最左到重复char这段扔掉),在这个过程中记录最大窗口长度
/*
* 利用滑动窗口原理;
* map<Character,Integer>存放字符对应的位置;
* 每遍历一个字符,都计算窗口大小:
* 计算左边界:map中是否存在该字符?存在:位置+1 ;不存在:0;
* 窗口大小:该字符位置-左边界+1;
* 比较最大窗口和当前计算的窗口;
*/
public int lengthOfLongestSubstring(String s) {
if(s==null ||s.length()==0){
return 0;
}
int max=0;
int leftBound=0;
Map<Character,Integer> map=new HashMap<Character,Integer>();
for(int i=0;i<s.length();i++){
char c=s.charAt(i);
//每次出现重复字符,则leftBound变为第一个重复字符的下一个;
leftBound=Math.max(leftBound,map.containsKey(c)?map.get(c)+1:0);
max=Math.max(max, i-leftBound+1);
map.put(c, i);
}
return max;
}