Concise 3ms recursive Java solution, beats 97.11% of submissions

  • 0

    Recursively build the solution of the nth iteration from the solution of the n-1th iteration. For each iteration, if the current character cur is the same as c, increment the counter. Otherwise, append its frequency and the character c and reset the counter and the character c.

    public class Solution {
        public String countAndSay(int n) {
            return countAndSay("1", n-1);
        private String countAndSay(String str, int itr) {
            if (itr == 0) return str;
            StringBuilder builder = new StringBuilder();
            int count = 0;
            char c = str.charAt(0);
            for (char cur : str.toCharArray()) {
                if (cur == c) {
                } else {
                    c = cur;
                    count = 1;
            return countAndSay(builder.toString(), itr-1);

Log in to reply

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