- 定义一个map数据结构存储(k,v),其中key值为字符,value值为字符位置,value+1,加1表示从字符位置后一个才开始不重复
- 我们定义不重复子串的开始位置为start,结束位置为end
- 随着end不断遍历向后,会遇到与【start,end】区间内字符相同的情况,此时将字符作为key值,获取其value值,并更新start,此时【start,end】区间内不存在重复字符
- 无论是否更新start,都会更新其map数据结构和结果ans。
- 时间复杂度:O(n)
代码:
public int lengthOfLongestSubstring(String s) {
int length=s.length();
int max=0;
//存放字符以及
Map<Character,Integer> map =new HashMap<>();
for (int start = 0,end=0; end <length ; end++) {
char element=s.charAt(end);
if (map.containsKey(element)){
//为了防止连续重复字符,这里要进行一次判断
//+1表示该元素后一个元素才是不重复字符串的开始
start=Math.max(map.get(element)+1,start);
}
max=Math.max(max,end-start+1);
//保存最后一个该结点的位置;
map.put(element,end);
}
return max;
}