Notes:

Edge cases:

1. It does not follow while(it.hasNext()) it.next(). So we need add has next check in next()

2. If index is out of boundary, which means all the chars are used out. Must handle this case.

class StringIterator {
    private String data;
    private int index;
    private char current;
    private int value;

    public StringIterator(String compressedString) {
        index = 0;
        data = compressedString;
        getData();
    }
    
    public char next() {
        if (hasNext()) {
            value--;
            return current;
        }
        return ' ';
    }
    
    public boolean hasNext() {
        if (value == 0) {
            getData();
        }
        return value > 0;
    }
    
    private void getData() {
        if (index >= data.length()) {
            return;
        }
        current = data.charAt(index);
        int i = index + 1;
        while (i < data.length()) {
            if (data.charAt(i) >= '0' && data.charAt(i) <= '9') {
                i++;
            } else {
                break;
            }
        }
        value = Integer.parseInt(data.substring(index + 1, i));
        index = i;
    }
}

/**
 * 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();
 */

 

posted on 2017-09-12 15:32  keepshuatishuati  阅读(115)  评论(0编辑  收藏  举报