share my java solution, using deque data structure


  • 0
    T
    public class StringIterator {
        Deque<Character> CharDq;
        Deque<Integer> NumDq;
        public StringIterator(String compressedString) {
            CharDq = new ArrayDeque<>();
            NumDq = new ArrayDeque<>();
            
            char[] array=compressedString.toCharArray();
            
            for(int i=0;i<compressedString.length();){
                CharDq.offer(array[i]);
                i++;
                int j=i;
                while(i<array.length&&array[i]>='0'&&array[i]<='9'){
                    i++;
                }
                int num=Integer.parseInt(compressedString.substring(j,i));
                NumDq.offer(num);
            }
        }
        
        public char next() {
            if(CharDq.isEmpty()){
                return ' ';
            }
            
            char c=CharDq.peekFirst();
            int num=NumDq.peekFirst();
            if(num==1){
                CharDq.pollFirst();
                NumDq.pollFirst();
                return c;
            }else{
                NumDq.pollFirst();
                num--;
                NumDq.offerFirst(num);
                return c;
            }
            
        }
        
        public boolean hasNext() {
            return !CharDq.isEmpty();
        }
    }
    
    /**
     * Your StringIterator object will be instantiated and called as such:
     * StringIterator obj = new StringIterator(compressedString);
     * char param_1 = obj.next();
     * boolean param_2 = obj.hasNext();
     */
    

Log in to reply
 

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