Share my java solution using queue

  • 0

    The basic idea is to put all the characters into a queue. Every time we want to put a character that is already in queue, just remove the same character in queue and all the characters before it. Then, we keep track with the size of queue all the time to find the maximum size.

    I don't think this algorithm is good, but it might be very simple.

    Here is my code:

    public int lengthOfLongestSubstring(String s) {
            int maxCount = 0;
            Queue<Character> q = new LinkedList<Character> ();
            for (int index = 0; index < s.length(); index++) {
                char c = s.charAt(index);
                if (q.contains(c)) {
                    char g = q.remove();
                    while (g != c) {
                        g = q.remove();
                if (maxCount < q.size()) {
                    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.