Java concise solution only with index


  • 0
    Y
    public class StringIterator {
    
        String str;
        int index;
        int count;
        int digit;
        
        public StringIterator(String compressedString) {
            str = compressedString;
            index = 0;
            count = 0;
            digit = 0;
            if (str.length() > 1) {
                calculateCount(index + 1);
            }
        }
        
        public char next() {
            if (count == 0) {
                return ' ';
            }
            char next = str.charAt(index);
            if (--count == 0) {
                index += digit + 1;
                if (index < str.length()) {
                    calculateCount(index + 1);
                }
            }
            return next;
        }
        
        public boolean hasNext() {
            return count == 0 ? false : true;
        }
        
        private void calculateCount(int start) {
            digit = 0;
            while (start < str.length() && str.charAt(start) >= '0' && str.charAt(start) <= '9') {
                count = count * 10 + str.charAt(start) - '0';
                start++;
                digit++;
            }
        }
    }
    
    /**
     * 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.