Java iterative solution with explanation, beat 75%


  • 0
    Base case: n = 0 print "1"
    for n = 1, look at previous string and write number of times a digit is seen and the digit itself. In this case,
    digit 1 is seen 1 time in a row... so print "1 1"
    for n = 2, digit 1 is seen two times in a row, so print "2 1"
    for n = 3, digit 2 is seen 1 time and then digit 1 is seen 1 so print "1 2 1 1"
    for n = 4 you will print "1 1 1 2 2 1"
    
        public String countAndSay(int n) {
            StringBuilder sb = new StringBuilder();
            sb.append('1');
            for(int i = 1; i < n; i++){
                char[] numbers = sb.toString().toCharArray();
                char pre = numbers[0];
                
                sb = new StringBuilder();
                int j = 0;
                while(j < numbers.length ){
                    int cnt = 0;
                    while(j<numbers.length && pre == numbers[j] ){
                        cnt++;
                        j++;
                    }
                    if(cnt>0){
                        sb.append(cnt);
                        sb.append(numbers[j-1]);
                        if(j < numbers.length){
                            pre = numbers[j];
                        }
                    }
                }
            }
            return sb.toString();
        }
    

Log in to reply
 

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