Java Solution, two Lists


  • 3

    One array for character another for corresponding count of that character.

    public class StringIterator {
        List<Character> chars = new ArrayList<>();
        List<Integer> counts = new ArrayList<>();
        int ptr = 0;
        
        public StringIterator(String str) {
            int i = 0;
            while (i < str.length()) {
                chars.add(str.charAt(i));
                int j = i + 1;
                while (j < str.length() && Character.isDigit(str.charAt(j))) j++;
                counts.add(Integer.parseInt(str.substring(i + 1, j)));
                i = j;
            }
        }
        
        public char next() {
            if (!hasNext()) return ' ';
            
            char result = chars.get(ptr);
            counts.set(ptr, counts.get(ptr) - 1);
            if (counts.get(ptr) == 0) ptr++;
            return result;
        }
        
        public boolean hasNext() {
            return ptr < chars.size();
        }
    }
    

  • 0
    M

    @shawngao This is not optimal if we want to fetch the next element 'lazily', not having to scan through it on initiation.


Log in to reply
 

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