zoukankan      html  css  js  c++  java
  • 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;
    
        }
    }
    
  • 相关阅读:
    MySQL--CREATE INDEX在各版本的优化
    MySQL--各版本DDL 操作总结
    MySQL--事务隔离级别RR和RC的异同
    MySQL--运维内参中的binlog_summary脚本
    认知:人性
    诉衷情
    初中生读物
    DTO和Entity转换
    layui开发常用插件列表
    mongodb配置
  • 原文地址:https://www.cnblogs.com/lxr-xiaorong/p/13438955.html
Copyright © 2011-2022 走看看