Java O(1) space, easy to understand with in line explanation


  • 0
    public class StringIterator {
        String str;
        int len;    //length of the string
        int idx;    //next processing index
        char curChar; //the char should return
        int num;    //number of curChar left
    
        public StringIterator(String compressedString) {
            str = compressedString;
            if(str == null || str.isEmpty() ||!Character.isLetter(str.charAt(0))){
                len=0;
            }else {
                len=str.length();
            }
            idx = 0;
            curChar = ' ';
            num =0;
            
        }
        
        public char next() {
            if(!hasNext()) return ' ';
            if(num>0){
                num--;
            }else if(idx<len) {
                curChar = str.charAt(idx++);
                if(idx<len && Character.isDigit(str.charAt(idx))){
                    while(idx<len && Character.isDigit(str.charAt(idx))){
                        num=num*10+(str.charAt(idx++)-'0');
                    }
                    num--;//for the current call
                }else{
                    num=0;
                }
            }
            return curChar;
        }
        
        public boolean hasNext() {
            return idx<len || num>0;  //have more characters left, or the last character still need to repeat more times 
        }
    }
    
    /**
     * Your StringIterator object will be instantiated and called as such:
     * StringIterator obj = new StringIterator(compressedString);
     * char param_1 = obj.next();
     * boolean param_2 = obj.hasNext();
     */
    

Log in to reply
 

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