无重复字符的最长子串

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

示例 1:

输入: “abcabcbb”
输出: 3
解释: 因为无重复字符的最长子串是 “abc”,所以其长度为 3。
示例 2:

输入: “bbbbb”
输出: 1
解释: 因为无重复字符的最长子串是 “b”,所以其长度为 1。
示例 3:

输入: “pwwkew”
输出: 3
解释: 因为无重复字符的最长子串是 “wke”,所以其长度为 3。
请注意,你的答案必须是 子串 的长度,“pwke” 是一个子序列,不是子串

解一:暴力法

public int lengthOfLongestSubstring(String s) {
        int res = 0;
        int n = s.length();
        for(int i = 0;i < n;i++){
            for(int j = i;j < n;j++){
                Set<Character> set = new HashSet<Character>();
                boolean flag = true;
                for(int k = i;k < j;k++){
                    if(set.contains(s.charAt(k))){
                        flag = false;
                        break;
                   }
                    set.add(s.charAt(k));
                }
                if(flag)
                    res = Math.max(res, j - i);
            }
        }
        return res;
    }

解二:滑动窗口
利用一个HashSet存储窗口内的已知元素,然好向右扩充该窗口,发现扩充元素在已知窗口内时则移去窗口最左边的元素,再将窗口左边右移一个元素,若不在,向set添加该扩充元素,窗口右边右移一位并此时更新结果。

public int lengthOfLongestSubstring(String s){
        int res = 0, left = 0, right = 0;
        int n = s.length();
        Set<Character> set = new HashSet<Character>();
        while (left < n && right < n){
            if(!set.contains(s.charAt(right))){
                set.add(s.charAt(right++));
                res = Math.max(res, right - left);
            }else {
                set.remove(s.charAt(left++));
            }
        }
        return res;
    }

解三:优化滑动窗口

public int lengthOfLongestSubstring(String s){
        int res = 0, left = 0, right = 0;
        int n = s.length();
        Map<Character, Integer> map = new HashMap<Character, Integer>();
        for(right = 0;right < n;right++){
            if(map.containsKey(s.charAt(right))){
                left = Math.max(left, map.get(s.charAt(right)));
            }
            res = Math.max(res, right - left + 1);
            map.put(s.charAt(right), right + 1);
        }
        return res;
    }

使用128大小的数组代替map,因为ASCII码一共128位。

public int lengthOfLongestSubstring(String s){
        int res = 0, left = 0, right = 0, n = s.length();
        int[] ascii = new int[128];
        for(;right < n;right++){
            if(ascii[s.charAt(right)] != 0){
                left = Math.max(left, ascii[s.charAt(right)]);
            }
            res = Math.max(res, right - left + 1);
            ascii[s.charAt(right)] = right + 1;
        }
        return res;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值