AC Answer by Using Queue (Why nobody mentions that?)


  • 1
    Y

    Iterate the whole string character by character. Add character into queue, if encounter a existing character, removeFirst from queue till removing that existing character. Record the size of the queue and compare it with max.

    class Solution {
        public int lengthOfLongestSubstring(String s) {
            ArrayDeque<Character> queue = new ArrayDeque<>();
            int max = 0;
            for (char c: s.toCharArray()) {
                while (queue.contains(c)) {
                    queue.removeFirst();
                }
                queue.add(c);
                max = Math.max(queue.size(), max);
            }
            return max;
        }
    }
    

  • 0
    A

    This is insane, never thought that we can do it using Queue.


Log in to reply
 

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