Straightforward Java solution no fancy data structure


  • 1
    Y

    The idea is straighforward.

    If the current character is not consumed (count > 0), output the current character.
    If current character is consumed (count == 0), fetch next character. If no more, output ' '

    public class StringIterator {
        String compressedString;
        Character cur;
        int count;
        int i;
      
        public StringIterator(String compressedString) {
            this.compressedString = compressedString;
            this.cur = null;
            this.i = 0;
            this.count = 0;
        }
        
        public char next() {
            if (count == 0) {
                if (i >= compressedString.length()) {return ' ';}
                cur = compressedString.charAt(i++);
                while (i < compressedString.length() && compressedString.charAt(i) >= '0' && compressedString.charAt(i) <= '9') {
                    count = 10 * count + (compressedString.charAt(i)-'0');
                    i++;
                }
            }
            count--;
            return cur;
        }
        
        public boolean hasNext() {
            return i < compressedString.length() || count != 0;
        }
    }
    

Log in to reply
 

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