Recursive 4ms


  • 0
    R
    public class Solution {
        public String countAndSay(int n) {
            if (n == 1) return "1";
            
            String prev = countAndSay(n-1);
            int count = 1;
            char[] arr = prev.toCharArray();
            char num = arr[0];
            StringBuilder cons = new StringBuilder();
            
            for (int i = 1; i < arr.length; i++) {
                if (arr[i] == num) {
                    count++;
                } else {
                    cons.append(count).append(num);
                    count = 1;
                    num = arr[i];
                }
            }
            
            cons.append(count).append(num);
            return cons.toString();
        }
    }
    

Log in to reply
 

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