Easy Java solution, recursion, each with 1 pass


  • 0
    B
    public String countAndSay(int n) {
        if (n == 1) return "1";
        String last = countAndSay(n - 1);
        int i = 0;
        int count = 0;
        char lastC = last.charAt(0);
        String result = "";
        while (i < last.length()) {
            char c = last.charAt(i);
            if (c == lastC) {
                count++;
            } else {
                result += count + "" + lastC;
                count = 1;
                lastC = c;
            }
            i++;
        }
        result += count + "" + lastC;
        return result;
    }

Log in to reply
 

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