Java nice code using HashSet


  • 2
    B
    public class Solution {
        public int lengthOfLongestSubstring(String s) {
            if (s == null || s.length() == 0) {
                return 0;
            }
            HashSet<Character> set = new HashSet<Character>();
            int start = 0;
            int res = 0;
            for (int i = 0; i < s.length(); i++) {
                char c = s.charAt(i);
                if (set.contains(c)) {
                    while (start < i && s.charAt(start) != c) {
                        set.remove(s.charAt(start));
                        start++;
                    }
                    start++;
                } 
                set.add(c);
                res = Math.max(res, i - start + 1);
            }
            
            return res;
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.