O(n) solution with pointer and char array


  • 0
    Q

    the solution is pretty simple.

    1. use char array to read the character, instead of string.charAt(idx) each time.
    2. record current char and its available quantity, that is the variable "left"
    3. each time we call next(), decrease "left" by 1. If the value of "left" is 0 after reduce, read the next char from char array and renew the value of "left".
    class StringIterator {
    
    	char currChar = 'a';
    	int left = 0;
    	int nextIdx = 0;
    	int len = 0;
    	char[] compressedString = null;
    
    	public StringIterator(String compressedString) {
    
    		if (compressedString != null && !compressedString.isEmpty()) {
    			this.compressedString = compressedString.toCharArray();
    			len = compressedString.length();
    			currChar = this.compressedString[nextIdx++];
    
    			char num = this.compressedString[nextIdx];
    			while (num >= '0' && num <= '9' && nextIdx < len) {
    				left = left * 10 + num - '0';
    				if (++nextIdx < len)
    					num = this.compressedString[nextIdx];
    			}
    		}
    	}
    
    	public char next() {
    		if (hasNext()) {
    			char res = currChar;
    			if (--left == 0 && nextIdx < len) {
    				currChar = compressedString[nextIdx++];
    				char num = compressedString[nextIdx];
    				while (num >= '0' && num <= '9' && nextIdx < len) {
    					left = left * 10 + num - '0';
    					if (++nextIdx < len)
    						num = compressedString[nextIdx];
    				}
    			}
    			return res;
    		} else
    			return ' ';
    	}
    
    	public boolean hasNext() {
    		return left > 0 || nextIdx < len;
    	}
    
    }
    

Log in to reply
 

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