An iterator which works like an iterator Java O(1) space


  • 1
    G
        char currentChar;
        Integer currCharCount;
        Integer currCharMaxCount;
        int index;
        String compressedString;
        public StringIterator(String compressedString) {
            index = 0;
            this.compressedString = compressedString;
        }
        
        public char next() {
            if(hasNext()){
                if(currCharCount == currCharMaxCount){
                    currentChar = compressedString.charAt(index);
                    currCharMaxCount = 0;
                    index++;
                    while(index<compressedString.length() && Character.isDigit(compressedString.charAt(index))){
                        currCharMaxCount = 10*currCharMaxCount + (compressedString.charAt(index++) - '0');
                    }
                    currCharCount = 0;
                }
                currCharCount++;
                return currentChar;
            }else return ' ';
            
        }
        
        public boolean hasNext() {
            return index<compressedString.length() || currCharCount < currCharMaxCount;
        }
    

Log in to reply
 

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