找出没有重复字母的最长子串
思路:通过map集合记录每个不同字符的索引位置,右指针每次移动时检索该索引,如果之前出现了,更新字符的索引值,并用max标识记录下循环中出现的最长字符串长度。
class Solution {
public int lengthOfLongestSubstring(String s) {
if (s.length()==0) return 0;
HashMap<Character, Integer> map = new HashMap<Character, Integer>();
int n=s.length();
//字串首尾指针
int left=-0,right=0;
//最长度标识符
int max =0;
while(right<n){
//更新子串左指针
if(map.containsKey(s.charAt(right))){
left = Math.max(left,map.get(s.charAt(right)) + 1);
}
//更新map中的索引值
map.put(s.charAt(right),right);
//更新最长度
max = Math.max(max, right - left +1);
++right;
}
//返回
return max;
}
}