0
点赞
收藏
分享

微信扫一扫

leetCode: 3. 无重复字符的最长子串

GhostInMatrix 2022-04-16 阅读 148
java

问题描述-原题链接

给定一个字符串 s ,请你找出其中不含有重复字符的 最长子串 的长度。

代码:

class Solution {
    public int lengthOfLongestSubstring(String s) {
        //基本思路:用一个HashMap去存储字符以及对应的index,采用滑动窗口求解
        int len = s.length();
        if(len==0)
        return 0;
        int max = 0;
        int left=0;
        HashMap<Character,Integer> map = new HashMap<Character,Integer>();
        for(int i=0;i<len;i++){
            if(map.containsKey(s.charAt(i))){
                left=Math.max(left,map.get(s.charAt(i))+1);
            }
            map.put(s.charAt(i),i);//没有字符就放入,有就替换
            max=Math.max(max,i-left+1);
        }
        return max;
    }
}
举报

相关推荐

0 条评论