No queue or list is used. A simple solution with explanation.


  • 0
    E

    Kindly advise if any part of the code could be improved! Thank you!

    public class StringIterator {
    
        // p is the pointer which will iterate from the beginning to the end of the input string
        private int p;
        // curr is the current character being iterated
        private char curr;
        // count is the count of current character
        private int count;
        // s is a duplicate of the input string
        private String s;
        
        public StringIterator(String compressedString) {
            s = compressedString;
            p = 0;
            count = 0;
            curr = compressedString.charAt(p);
        }
        
        public char next() {
            if (hasNext()) {
                // If there are still current characters, update count and return a current character.
                if (count > 0) {
                    count--;
                    return curr;
                }
                // If there is not any current character, use p to get the next character in the input string.
                else {
                    curr= s.charAt(p);
                    p++;
                    count = 0;
                    // To get the new count
                    while (p < s.length() && Character.isDigit(s.charAt(p))) {
                        count = count * 10 +  Character.getNumericValue(s.charAt(p));
                        p++;
                    }
                    count--;
                    return curr;
                }
            }
            else 
                return ' ';
        }
        
        // Two conditions mean "hasNext()": 
        // (1) count of current character is not zero;
        // (2) pointer p has not reached the end of the input string.
        public boolean hasNext() {
            return count != 0 || p < s.length();
        }
    }
    

Log in to reply
 

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