A bit of Java 8, regex and very short solution

  • 5

    The idea is simple, to use regex to seperate out the characters and their frequencies and then loop through them.

    public class StringIterator {
        int i;
        String[] arr;
        int[] counts;
        public StringIterator(String str) {
            arr = str.split("\\d+");
            counts = Arrays.stream(str.substring(1).split("[a-zA-Z]+")).mapToInt(Integer::parseInt).toArray();
        public char next() {
            if(!hasNext()) return ' ';
            char ch = arr[i].charAt(0);
            if(--counts[i] == 0) ++i;
            return ch;
        public boolean hasNext() {
            if(i == arr.length) return false;
            return true;

  • 1

    @johnyrufus16 said in A bit of Java8, regex and very short solution:


    Hi @johnyrufus16 I was also trying via regex but count not figure out why we need to take str.substring(1).split("[a-zA-Z]+") . When I am doing str.split("[a-zA-Z]+") I get first element in the array as spaces .. Do you know the reason why ?

  • 0

    @bharaniabhishek123 if we split the whole string, then the empty string to the left of the first regex match appears in the result, thats the reason, i split the string after the first character

  • 1

    I like the Java 8 stream() method

Log in to reply

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