Java Lazy Fetch Solution


  • 0
    C

    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()){
                list.add(ch);
            }
            cur= list.listIterator();
        }
        
        public char next() {
            if (hasNext()){
                count--;
                return curCh;
            } return ' ';
        }
        
        public boolean hasNext() {
            if (count >0) return true;
            else {
                if (cur.hasNext()){
                    curCh= cur.next();
                    count = cur.next() - '0';
                    while (cur.hasNext()){
                        char next= cur.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.