easy java solution, 5ms time


  • 0
    Y

    A easy recursive solution: count the number of each different digitals and generate a string.

    public class Solution {
        public String countAndSay(int n) {
            
            if (n == 0) return "0";
            if (n == 1) return "1";
            
            String last = countAndSay(n-1);
            StringBuffer sb = new StringBuffer();
            
            char cur = '0';
            int cnt = 0;
            for (int i=0; i<last.length(); i++) {
                if (last.charAt(i) != cur) {
                    if (cnt > 0) {
                        sb.append(cnt).append(cur);
                        cnt = 0;
                    }
                    cur = last.charAt(i);
                }
                cnt ++;
            }
            if (cnt > 0) {
                sb.append(cnt).append(cur);
            }
            
            return sb.toString();
        }
    }
    

Log in to reply
 

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