Recursive Java Solution (4 ms runtime)


  • 0
    V

    Observe that the nth sequence is composed by decoding the (n-1)th sequence. In the base case just return "1" for the seed of the sequence, similar to Fibonacci

    public static String countAndSay(int n) {
        if(n == 1)
            return "1";
        return decode( countAndSay(n-1) );
    }
    
    private static String decode(String s)
    {
        StringBuilder sb = new StringBuilder();
    
        int currentCount = 0;
        char prevChar = '0';
    
        for(int i = 0; i < s.length(); i++)
        {
            if(prevChar != '0' && s.charAt(i) != prevChar)
            {
                sb.append(currentCount);
                sb.append(prevChar);
                currentCount = 0;
            }
            currentCount++;
            prevChar = s.charAt(i);
        }
        sb.append(currentCount);
        sb.append(prevChar);
    
        return sb.toString();
    }

Log in to reply
 

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