Simple Java recursion solution


  • 0
    J
    public class Solution {
        public String countAndSay(int n) {
            return helper("1", 1, n);
        }
        
        public String helper(String input, int round, int n) {
            if (n == round) return input;
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < input.length(); i++) {
                int count = 1;
                while (i + 1 < input.length() && input.charAt(i) - '0' == input.charAt(i + 1) - '0') {
                    count++;
                    i++;
                }
                sb.append(count);
                sb.append(input.charAt(i));
            }
            round++;
            if (round == n) {
                return sb.toString();
            } else 
                return helper(sb.toString(), round, n);
        }
    }
    

    recursion func will return a string and it is used for the input for next recursion call. variable round can be considered as roundth. When round equals to n, result has been found and should be returned


Log in to reply
 

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