A fast java solution


  • 0
    S
    public class Solution {
        public String countAndSay(int n) {
            if(n < 1)
                return "";
            if(n == 1)
                return "1";
            char[] chars = countAndSay(n - 1).toCharArray();
            
            char num = chars[0];
            int count = 1, i, len = chars.length;
            StringBuilder builder = new StringBuilder();
            
            for(i = 1;i<len;i++) {
                if(chars[i] == num)
                    count++;
                else {
                    char[] str = new char[2];
                    str[0] = (char)(count + '0');
                    str[1] = num;
                    builder.append(new String(str));
                    num = chars[i];
                    count = 1;
                }
            }
            
            char[] str = new char[2];
            str[0] = (char)(count + '0');
            str[1] = num;
            builder.append(new String(str));
            
            return builder.toString();
        }
    }

Log in to reply
 

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