Post my own DP-based solution written in Java.


  • 0
    Z

    Here is my easy understood Java solution. A DP approach.
    '''
    class Solution {
    public String countAndSay(int n) {
    if(n<=0) return null;

        String[] dp = new String[n+1];
        dp[0] = null;
        dp[1] = "1";
        for(int i=1; i<n; i++) {
            String s = dp[i];
            StringBuilder sb = new StringBuilder();
            for(int j=0; j<s.length(); j++) {
                char c = s.charAt(j);
                int count = 1;
                while(++j<s.length()&&s.charAt(j)==c) {
                    count++;
                }
                sb.append(count);
                sb.append(c);
                j--;
            }
            dp[i+1] = sb.toString();
        }
        return dp[n];
    }
    

    }
    '''


Log in to reply
 

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