Java Lazy Fetch Solution

  • 0

    Most of the solutions I saw store either the string or a list/queue/etc. I just want to offer a solution that implements lazy fetch, which is how iterators should be implemented in my opinion. Please let me know if anyone has an idea to improve this code.

    class StringIterator {
        private ListIterator<Character> cur;
        private int count =0;
        private char curCh =' ';
        public StringIterator(String compressedString) {
            List<Character> list= new ArrayList<>();
            for (char ch: compressedString.toCharArray()){
            cur= list.listIterator();
        public char next() {
            if (hasNext()){
                return curCh;
            } return ' ';
        public boolean hasNext() {
            if (count >0) return true;
            else {
                if (cur.hasNext()){
                    count = - '0';
                    while (cur.hasNext()){
                        char next=;
                        if (next>='0' && next<= '9') {
                            count= count*10+ (next-'0');
                        } else break;
                    if (cur.hasNext()) cur.previous();
                    return true;
                return false;

Log in to reply

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