003无重复字符的最长子串

写在前面,参考的力扣官网的画解算法

滑动窗口

class Solution {
    public int lengthOfLongestSubstring(String s) {

        //定义字符串长度,距离
        int n=s.length(),ans=0;

        //用什么装start指针
        //定义一个map数据结构存储(k,v),期中key为字符,value值为字符位置+1
        //+1表示从字符位置后一个才开始不重复
        Map<Character,Integer>map=new HashMap<>();

        //定义不重复字符串的开始位置为start,结束位置为end
        for(int end=0,start=0;end<n;end++){
            char alpha=s.charAt(end);

             //什么时候更新start?start更新为多少?
            //随着end的不断向后遍历,会遇到与[start,end]区间内字符相同的情况
            if(map.containsKey(alpha)){

                //map中取的是什么?
                //此时将字符作为key值,获取其value值,并更新start,
                //此时[start,end]区间内不存在重复字符
                start=Math.max(map.get(alpha),start);

            }

            //不论是否更新start,都会更新其map数据结构和结果ans
            ans=Math.max(ans,end-start+1);
            //map中存的是什么?
            //当前位置的元素,当前位置的后一个下标
            map.put(s.charAt(end),end+1);
        }
        return ans;

    }
}
原文地址:https://www.cnblogs.com/lxr-xiaorong/p/13438955.html