My short Java answer using recursion


  • 0
    L

    Here is my short java answer using recursion.

    public class Solution {
        public String countAndSay(int n) {
            if (n <= 1) return "1";
            String last = countAndSay(n-1);
            StringBuilder s = new StringBuilder();
            int count = 1;
            for (int i = 0; i < last.length(); i++) {
                if (i == last.length() - 1 || last.charAt(i) != last.charAt(i+1)) {
                    s.append(count);
                    s.append(last.charAt(i));
                    count = 1;
                }
                else count++;
            }
            return s.toString();
        }
    }
    

Log in to reply
 

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