Share my short java solution using queue


  • 0
    B

    The basic idea is to use a queue of characters to represent the substring without repeating characters.
    To do this, we put characters in the string into the queue one by one from left to right. Every time before we want to enqueue a character c that is exist in queue, we need to continuously remove characters in FIFO order until we remove c. Then we can keep track with the size of queue to find out the maximum size of substring without repeating characters.

    This solution may not be very fast, but I think it is pretty straight-forward.

    Here is my code:

    public int lengthOfLongestSubstring(String s) {
            int maxCount = 0;
            Queue<Character> q = new LinkedList<> ();
            for (char c: s.toCharArray()) {          
                while (q.contains(c))
                    q.remove();
                q.add(c);
                maxCount = Math.max(maxCount, q.size());
            }
            return maxCount;
        }
    

Log in to reply
 

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