美文网首页
无重复字符的最长子串练习

无重复字符的最长子串练习

作者: 月如钩dgf | 来源:发表于2022-05-23 23:54 被阅读0次

题目描述:

题目描述:
给定一个字符串 s ,请你找出其中不含有重复字符的 最长子串 的长度。
示例 1:
输入: s = "abcabcbb"
输出: 3
解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。
示例 2:
输入: s = "bbbbb"
输出: 1
解释: 因为无重复字符的最长子串是 "b",所以其长度为 1。

笨办法暴力破解法:

    public static int maxLength(String s) {
        int a = 0; // 计数
        int max = 0; // 最大子串长度
        String newStr = new String(); // 定义新字符串
        char[] chars = s.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            newStr = chars[i] + "";
            a = 1;
            for (int j = i + 1; j < chars.length; j++) {
                if (!newStr.contains(chars[j] + "")) {
                    a++;
                    newStr = newStr + chars[j];
                } else {
                    max = Math.max(max, a);
                    break;
                }
                max = Math.max(max, a);
            }
            max = Math.max(max, a);
        }
        return max;
    }

窗口模式解答方式:

窗口方式示例图
    public static int mx2(String s) {
        int max = 0;
        Set<Character> list = new HashSet<>();
        int right = 0; // 右指针
        int left = 0; // 左指针
        while (right < s.length()) {
            if (list.contains(s.charAt(right))) {
                list.remove(s.charAt(left));
                ++left;  // 有重复左移动
            } else {
                list.add(s.charAt(right));
                ++right;  // 右移指针
            }
            max = Math.max(max, right - left);
        }
        return max;
    }

每天进步一点点~2022年5月23日

相关文章

网友评论

      本文标题:无重复字符的最长子串练习

      本文链接:https://www.haomeiwen.com/subject/amwdprtx.html