LeetCode:无重复字符的最长字串

方法一:

java 复制代码
class Solution {
    public int lengthOfLongestSubstring(String s) {
        //记录当前有哪些字符
        Set<Character> windoeSet = new HashSet<>();

        int left = 0;
        //最大长度
        int maxLength = 0;
        //挨个遍历
        for(int right = 0;right < s.length();right++){
            //用于存放
            char incomingChar = s.charAt(right);

            while(windoeSet.contains(incomingChar)){
                //用于删除
                char outcomingChar = s.charAt(left);
                windoeSet.remove(outcomingChar);
                left++;
            }
            windoeSet.add(incomingChar);
            maxLength = Math.max(maxLength,right - left + 1);
        }
        return maxLength;
    }
}

方法二:

java 复制代码
class Solution {
    public int lengthOfLongestSubstring(String s) {
        //记录每个字符上次出现的位置
        int[] indexMap = new int[128];

        int left = 0;
        int maxLength = 0;

        for(int right = 0;right < s.length();right++){
            //获取当前字符的ASCII码(Java里的char可以直接当作int用)
            char c = s.charAt(right);
            //查这个字符上次出现的位置
            //没出现过,indexMap[c]就是0,Math.max会让left保持原地不变
            //出现过,left直接到它上次出现的下一个位置(不能往回退)
            left = Math.max(left,indexMap[c]);
            maxLength = Math.max(maxLength,right - left +1);
            //存位置时,将位置+1
            indexMap[c] = right + 1;
        }
        return maxLength;
    }
}

时间:

第二种方法少一个while循环;相对于第一种的HashSet,第二种使用数组,时间提升;

第一段的remove产生内存垃圾,Java的垃圾回收器清理他们,拖慢时间

空间:

第一种使用Character涉及到对象,吃内存;而第二种只使用数组

相关推荐
故事和你916 小时前
洛谷-数据结构1-1-线性表1
开发语言·数据结构·c++·算法·leetcode·动态规划·图论
脱氧核糖核酸__6 小时前
LeetCode热题100——53.最大子数组和(题解+答案+要点)
数据结构·c++·算法·leetcode
脱氧核糖核酸__7 小时前
LeetCode 热题100——42.接雨水(题目+题解+答案)
数据结构·c++·算法·leetcode
王老师青少年编程8 小时前
csp信奥赛C++高频考点专项训练之贪心算法 --【线性扫描贪心】:数列分段 Section I
c++·算法·编程·贪心·csp·信奥赛·线性扫描贪心
王老师青少年编程8 小时前
csp信奥赛C++高频考点专项训练之贪心算法 --【线性扫描贪心】:分糖果
c++·算法·贪心算法·csp·信奥赛·线性扫描贪心·分糖果
_日拱一卒8 小时前
LeetCode:2两数相加
算法·leetcode·职场和发展
py有趣8 小时前
力扣热门100题之零钱兑换
算法·leetcode
董董灿是个攻城狮8 小时前
Opus 4.7 来了,我并不建议你升级
算法
无敌昊哥战神8 小时前
【保姆级题解】力扣17. 电话号码的字母组合 (回溯算法经典入门) | Python/C/C++多语言详解
c语言·c++·python·算法·leetcode
脱氧核糖核酸__8 小时前
LeetCode热题100——238.除了自身以外数组的乘积(题目+题解+答案)
数据结构·c++·算法·leetcode