Java easy to understand solution


  • 0
    F
    private char lastChar;
    private String s;
    private int index = 0;
    private int count = 1;
    
    public StringIterator(String compressedString) {
    	s = compressedString;
    }
    
    public char next() {
    	if (count > 1) {
    		count--;
    		return lastChar;
    	} else if (index == s.length())
    		return ' ';
    	else {
    		char c = s.charAt(index++);
    		int start = index;
    		while (index < s.length() && s.charAt(index) <= '9' && s.charAt(index) >= '0') {
    			index++;
    		}
    		count = Integer.valueOf(s.substring(start, index));
    		if (count > 1)
    			lastChar = c;
    		return c;
    	}
    }
    
    public boolean hasNext() {
    	return index < s.length() || count > 1;
    }

Log in to reply
 

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