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


  • 0
    W

    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) {
                    count++;
                } else {
                    builder.append(count);
                    builder.append(c);
                    c = cur;
                    count = 1;
                }
            }
            
            builder.append(count);
            builder.append(c);
            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.