Java solution using TreeMap


  • 0
    S
    class StringIterator {
        private static TreeMap<Long, Character> treeMap;
        private static long length;
        private static long index;
        
        public StringIterator(String compressedString) {
            treeMap = new TreeMap<>();
            length = 0;
            index = 0;
            
            int len = compressedString.length();
            
            // uncompress the compressed string
            // and store in TreeMap
            for(int i=0; i<len;) {
                // letter
                char ch = compressedString.charAt(i++);
                
                // find the count of ch
                long count = 0;
                while(i<len && Character.isDigit(compressedString.charAt(i)))
                    count = count*10 + (compressedString.charAt(i++)-'0');
                
                treeMap.put(length, ch);
                length += count;
            }
        }
        
        public char next() {
            if(index >= length) return ' ';
            
            // returns the greatest key less than or equal to key
            long floorKey = treeMap.floorKey(index++);
            return treeMap.get(floorKey);
        }
        
        public boolean hasNext() {
            return index < length;
        }
    }
    

Log in to reply
 

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