Java Code O(1) space O(n) time Use two pointers


  • 0
    M
    public class StringIterator {
        int nLoc = 0;
        int lLoc = 0;
        String curr = "";
        int count = 0;
        char output;
        public StringIterator(String compressedString) {
            curr = compressedString;
        }
        
        public char next() {
            
            if (count > 0) {
                count--;
                return output;
            }
            if (lLoc >= curr.length() || nLoc >= curr.length()) return ' ';
            
            if (curr.charAt(lLoc) - '0' > 9) {
                output = curr.charAt(lLoc);
                nLoc = lLoc + 1;
                while (nLoc < curr.length() && curr.charAt(nLoc) - '0' < 10) {
                    count = count * 10 + curr.charAt(nLoc) - '0';
                    nLoc++;
                }
                lLoc = nLoc;
            }
            count--;
            return output;
        }
        
        public boolean hasNext() {
            return ((nLoc < curr.length() && lLoc < curr.length()) || count > 0);
        }
    }
    
    /**
     * 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();
     */
    

Log in to reply
 

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