Recursive java solution


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

Log in to reply
 

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