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(); }Design Compressed String Iterator