LeetCode热题100——无重复字符的最长字串

方法:滑动窗口

滑动窗口题型的基本模板:

for (int l = 0, r = 0; r < n; r++){
//外层移动右边界,里层的循环移动左边界
    while(l <= r && check()){ 
       //移动左边界
    }

} 

放到本题上就是:

移动右边界,判断当前是否含有该字符,并移动左边界到不包含该字符的位置,移动的同时删除中间已经不需要包括的字符

class Solution {
    public int lengthOfLongestSubstring(String s) {
        char[] ss = s.toCharArray();
        Set<Character> set = new HashSet<>();
        int res = 0;
        for(int left = 0, right = 0; right < s.length(); right++){
            char ch = ss[right];
            while(set.contains(ch)){
                set.remove(ss[left]);
                left++;
            }
            set.add(ss[right]);
            res = Math.max(res, right - left + 1);
        }
        return res;
    }
}

我还用Map写了,和模板会有出入,时间复杂度还是O(N)

里层少了层循环

class Solution {
    public int lengthOfLongestSubstring(String s) {
        Map<Character,Integer> map = new HashMap<>();
        int length = s.length();
        int ans = 0;
        int tempAns = 0;
        int l = 0,r =0;
        while(r < length){
            if(!map.containsKey(s.charAt(r)) || map.get(s.charAt(r)) < l){
                tempAns++;
            }else{
                ans = Math.max(ans,tempAns);
                l = map.get(s.charAt(r)) + 1;
                tempAns = r - l + 1;
            }
            map.put(s.charAt(r),r);
            r++;
        }
        ans = Math.max(ans,tempAns);
        return ans;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值