Java Concise Single Queue Solution


  • 10
    public class StringIterator {
        
        Queue<int[]> queue = new LinkedList<>();
        
        public StringIterator(String s) {
            int i = 0, n = s.length();
            while (i < n) {
                int j = i+1;
                while (j < n && s.charAt(j) - 'A' < 0) j++;
                queue.add(new int[]{s.charAt(i) - 'A',  Integer.parseInt(s.substring(i+1, j))});
                i = j;
            }
        }
        
        public char next() {
            if (queue.isEmpty()) return ' ';
            int[] top = queue.peek();
            if (--top[1] == 0) queue.poll();
            return (char) ('A' + top[0]);
        }
        
        public boolean hasNext() {
            return !queue.isEmpty();
        }
    
    }
    

  • 0
    T

    if (--top[1] == 0) queue.poll();
    About this line, will it update the counter in queue?
    Why the next time peeking don't get the same value?
    Thanks.


  • 0

    Another solution using Stack and self-defined Class

    class Node{
            char key;
            int num;
            public Node(char key, int num){
                this.key = key;
                this.num = num;
            }
        }
        Stack<Node> stack;
        public StringIterator(String compressedString) {
            this.stack = new Stack<Node>();
            int right = compressedString.length() - 1;
            while(right > 0){
                int left = right;
                while(left > 0 && Character.isDigit(compressedString.charAt(left))){
                    left --;
                }
                Node cur = new Node(compressedString.charAt(left), Integer.valueOf(compressedString.substring(left + 1, right + 1)));
                stack.push(cur);
                right = left - 1;
            }
        }
        
        public char next() {
            if(stack.isEmpty()) return ' ';
            Node cur = stack.pop();
            char res = cur.key;
            if(cur.num > 1){
                cur.num -= 1;
                stack.push(cur);
            }
            return res;
        }
        
        public boolean hasNext() {
            return !stack.isEmpty();
        }
    

  • 1
    I

    @tywang said in Java Concise Single Queue Solution:

    peeking

    Actually, full code should be

        top[1] = top[1] - 1;
        if (top[1] == 0) queue.poll();
    

    so, yes. it will update the counter in queue and next time peek(), the value has been changed.

    FYI
    An array is an object in Java.


Log in to reply
 

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