Design and implement a data structure for a compressed string iterator. It should support the following operations:nextandhasNext.

The given compressed string will be in the form of each letter followed by a positive integer representing the number of this letter existing in the original uncompressed string.

next()- if the original string still has uncompressed characters, return the next letter; Otherwise return a white space.
hasNext()- Judge whether there is any letter needs to be uncompressed.

class StringIterator {
    private LinkedList<Character> q1;
    private LinkedList<Integer> q2;

    public StringIterator(String compressedString) {
        q1 = new LinkedList<>();
        q2 = new LinkedList<>();

        int num = 0;
        for(int i = 0; i < compressedString.length(); i++) {
            char c = compressedString.charAt(i);

            if(i == compressedString.length() - 1) {
                num = num * 10 + (c - '0');
                q2.offerLast(num);
                break;
            }
            if((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {
                q1.offerLast(c);

                if(i > 0)
                    q2.offerLast(num);
                num = 0;
            } else if(c >= '0' && c <= '9') {
                num = num * 10 + (c - '0');
            }
        }
    }

    public char next() {
        if(!hasNext())
            return ' ';

        char c = q1.peekFirst();
        int count = q2.poll();

        if(count == 1) {
            q1.pollFirst();
        } else {
            q2.offerFirst(count - 1);
        }

        return c;
    }

    public boolean hasNext() {
        return q1.size() > 0;
    }
}

/**
 * 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();
 */

results matching ""

    No results matching ""