Java Solution with comments , easy to understand


  • 0
    M
    public class StringIterator {
        
        private int len;
        private int currIndex;
        private int noOfTimes;
        private String str;
        private char currChar;
    
        public StringIterator(String compressedString) {
            this.str = compressedString;
            this.len = compressedString.length();
            this.currIndex = 0;
        }
        
        public char next() {
            
            // Check if the character already returned by the previous next() operation has more than one occurrence
            // If yes, then return it again and decrease the occurrence by 1
            if (this.noOfTimes > 1) {
                this.noOfTimes--;
                return this.currChar;
            }
            
            // check if we have reached the end of string.
            // We will reach the end of string after we have returned all the number of occurrences of the last character 
            // and the previous if block gives false. 
            // So if this is true, return a space (' ')
            if (this.currIndex >= this.len) {
                return ' ';
            }
            
            // Captures the current character and stores it in currChar.
            this.currChar = this.str.charAt(this.currIndex);
            
            this.currIndex++;
            String number = "";
            
            while (this.currIndex < this.len && this.str.charAt(this.currIndex) >= '0' && this.str.charAt(this.currIndex) <= '9') {
                number += this.str.charAt(this.currIndex) + "";
                this.currIndex++;
            }
            
            this.noOfTimes = Integer.parseInt(number);
            return this.currChar;
        }
        
        public boolean hasNext() {
            
            if (this.noOfTimes > 1) {
                return true;
            } else if (currIndex >= len){
                return false;
            } else {
                return true;
            }
        }
    }
    

Log in to reply
 

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