Java solution using a backing Scanner


  • 0
    J
    import java.util.Scanner;
    
    public class StringIterator {
    	protected Scanner scanner;
    	protected char current;
    	protected int remaining;
    
    	public StringIterator(String compressed) {
    		scanner = new Scanner(compressed);
    		scanner.useDelimiter("(?<=\\d+)(?=\\p{Alpha})|(?<=\\p{Alpha})(?=\\d+)");
    		current = 0;
    		remaining = 0;
    	}
    
    	public char next() {
    		while (remaining == 0) {
    			if (scanner.hasNext()) {
    				current = scanner.next().charAt(0);
    				remaining = scanner.nextInt();
    			} else {
    				return ' ';
    			}
    		}
    		remaining -= 1;
    		return current;
    	}
    
    	public boolean hasNext() {
    		return remaining > 0 || scanner.hasNext();
    	}
    }
    
    

Log in to reply
 

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