Fast Java Solution


  • 0
    B
    class StringIterator {
    
        private String str;         // the compressedString
        private int pos;            // position of next letter
        private char c;             // the current letter
        private int count;          // number of times current letter remain
        
        public StringIterator(String compressedString) {
            this.str = compressedString;    // set str = compressedString
            this.pos = 0;                   // the first letter is at position 0
            this.c = ' ';                   // set c to any character
            this.count = 0;                 // set count to 0 so first time use next() will read the first letter
        }
        
        public char next() {
            if (pos == str.length() && count == 0) {
                // if no letter remain, return empty space
                return ' ';
            } else if (count == 0) {
                // else if no current letter exists, read next letter and count
                
                c = str.charAt(pos++);
                while (pos < str.length()) {
                    int ord = (int) str.charAt(pos);
                    if (ord < 48 || ord > 57) break;
                    count = count * 10 + (ord - 48);
                    pos++;
                }
            }
            //return the letter and reduce the count
            
            count--;
            return c;
        }
        
        public boolean hasNext() {
            return count > 0 || pos < str.length();
        }
    }
    

Log in to reply
 

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