Java Solution Using Deque and HashSet


  • 0
    D
    public class Solution {
        public int lengthOfLongestSubstring(String s) {
            if (s.length() == 0 || s == null) {return 0;}
            Deque<Character> q = new LinkedList<>();
            Set<Character> set = new HashSet<>();
            int max = Integer.MIN_VALUE;
            for (char c : s.toCharArray()) {
                while (!set.add(c)) {
                    set.remove(q.pollFirst());
                }
                q.offerLast(c);
                set.add(c);
                max = Math.max(max,q.size());
            }
            return max;
        }
    }

Log in to reply
 

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