3、无重复最长字符串

题目

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

  • 示例

    输入 s="abcabcbb"

    输出 3

    因为无重复字符的最长子串是 "abc",所以其长度为 3。

  • 示例

    输入: s = "bbbbb"
    输出: 1
    解释: 因为无重复字符的最长子串是 "b",所以其长度为 1。

  • 示例

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

题解

无重复字符串.jpg
    private static int StringLength(String str) {
        Set hasSet = new HashSet();
        int nums = str.length();
        int ans = 0;
        for (int i = 0; i < nums; i++) {
            int index = i;
            while (index < nums && !hasSet.contains(str.charAt(index))) {
                hasSet.add(str.charAt(index));
                index++;
            }
            ans = Math.max(ans, index-i);
            hasSet.clear();
        }
        return ans;
    }

你可能感兴趣的:(3、无重复最长字符串)