Recursive JAVA solution (simple and fast)


  • 0
    C
    class Solution {
        public String countAndSay(int n) {
            if (n == 1) return "1";
            StringBuilder sb = new StringBuilder();
            String s = countAndSay(n - 1);
            for (int i = 0; i < s.length(); ) {
                int counter = 1;
                while (i < s.length() - 1 && s.charAt(i) == s.charAt(i + 1)) {
                    counter++;
                    i++;
                }
                sb.append(counter);
                sb.append(s.charAt(i));
                i++;
            }
            return sb.toString();
        }
    }
    

Log in to reply
 

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