Simple and clean recursion solution


  • 0
    public class Solution {
        public String countAndSay(int n) {
            if (n < 0) return null;
            if (n == 1) return "1";
            return recurse("1", 1, n - 1);
        }
        
        private String recurse(String s, int level, int n) {
            int count = 1;
            char current = s.charAt(0);
            StringBuilder sb = new StringBuilder();
            if (s.length() == 1) {
                sb.append(count).append(current);
            }
            for (int i = 1; i < s.length(); i++) {
                char newChar = s.charAt(i);
                if (current == newChar) {
                    count++;
                } else {
                    sb.append(count).append(current);
                    current = newChar;
                    count = 1;
                }
                if (i == s.length() - 1) {
                    sb.append(count).append(current);
                }
            }
            if (level >= n) {
                return sb.toString();
            } else {
                return recurse(sb.toString(), level + 1, n);
            }
        }
    }
    

Log in to reply
 

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