Simple Java iterate once queue + visited array


  • 0
    A
    class Solution {
        public int lengthOfLongestSubstring(String s) {
            if(s.length() < 2)      return s.length();
            Queue<Character> q = new LinkedList<Character>();
            boolean[] record = new boolean[255];
            int answer = 1;
            
            for(int i = 0 ; i < s.length(); i++) {
                char c = s.charAt(i);
                if(record[c]) {
                    answer = Math.max(answer, q.size());
                    while(q.peek() != c){
                        record[q.poll()] = false;
                    }
                    record[q.poll()] = false;
                }
                record[c] = true;
                q.add(c);
            }
            answer = Math.max(answer, q.size());
            return answer; 
        }
    }
    

Log in to reply
 

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