Leetcode-3 无重复字符的最长子串

作者: itbird01 | 来源:发表于2021-10-27 06:57 被阅读0次

    3. 无重复字符的最长子串

    解题思路

    1.双层for循环,遍历字符串
    2.将遍历到的字符,add到hashset中,如果add失败,则说明此次遍历,set中已有重复元素,此时退出循环
    3.将保留的result与set.size对比,将result保持为最大值
    4.循环1~3,直到遍历到字符串末尾
    5.此时result为最长字符串长度

    解题遇到的问题

    后续需要总结学习的知识点

    1.其他解法?

    ##解法1
    class Solution {
        public static int lengthOfLongestSubstring(String s) {
            int result = 0;
            HashSet<Character> set = new HashSet<Character>();
            for (int i = 0; i < s.length(); i++) {
                set.clear();
                for (int j = i; j < s.length(); j++) {
                    if (!set.add(s.charAt(j))) {
                        break;
                    }
                }
                if (set.size() >= result) {
                    result = set.size();
                }
            }
            return result;
        }
    }
    

    相关文章

      网友评论

        本文标题:Leetcode-3 无重复字符的最长子串

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