寻找字符串中最大不重复字符串长度

 public static int lengthOfLongestSubstring(String s) {
        //设置滑动窗口
        HashSet<Character> removeSet = new HashSet<>();
        // 滑动窗口中字符串
        String removeStr="";
        // 存储最后结果信息
        HashSet<Character> resultSet = new HashSet<>();
        String resultStr = "";
        // 存储最长字符串长度
        int maxLength = 0;
        int removeIndex = 0;
        // 循环是 从 不同 startIndex 开始
        for (int startIndex = 0; startIndex < s.length(); startIndex++) {
            // 不在移动窗口中,则将当前字符追加到滑动窗口中
            while (removeIndex<s.length() && !removeSet.contains(s.charAt(removeIndex))) {
                removeSet.add(s.charAt(removeIndex));
                removeStr=removeStr+s.charAt(removeIndex);
                // 滑动窗口
                removeIndex++;
            }

            // 遇到在滑动窗口中存在的字符串时,从下一个起点开始重复
            // 此时需要记录当前滑动窗口中数据长度或字符串
            maxLength = Math.max(maxLength, removeSet.size());
            if (resultSet.size()< removeSet.size()) {
                resultSet.clear();
                resultSet.addAll(removeSet);
                resultStr= removeStr;
            }
            // 开启下一次滑动前 将滑动窗口第一个节点数据溢出
            removeSet.remove(s.charAt(startIndex));
            removeStr = removeStr.substring(1);
        }
        return maxLength;
    }
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容