Java Recursive solution


  • 1
    W
    public class Solution {
    public String countAndSay(int n) {
        //base case
        if(n == 1) return "1";
        
        String previous = countAndSay(n - 1);
        StringBuilder resultBuilder = new StringBuilder();
        char a = previous.charAt(0);
        //char b = previous.charAt(0);
        int count = 0;
        int strLength = previous.length();
        for(int i = 0; i < strLength; ++i){
            if(a == previous.charAt(i)){
                count++;
            }else{
                resultBuilder.append(count);
                resultBuilder.append(a);
                a = previous.charAt(i);
                count = 1;
            }
        }
        resultBuilder.append(count);
        resultBuilder.append(a);
        return resultBuilder.toString();
    }
    

    }


Log in to reply
 

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