20 October 2021

Leetcode 38. Count and Say

by Xin Hong

I use the recursive solution, the logic is the same as the dp solution. Suppose we know countAndSay(n-1), simply initialize a StringBuilder and iterate through the string. What we want is conservative characters, so we use curr to track the last character. When curr != c[i], add counter and the number.

class Solution {
    public String countAndSay(int n) {
		// base case
        if (n == 1) {
            return new String("1");
        }
        else {
            char[] c = countAndSay(n-1).toCharArray();
            StringBuilder sb = new StringBuilder();
            char curr = '.';
            int counter = 0;
            for (int i = 0; i < c.length; i++) {
                if (curr == '.') {
                    curr = c[i];
                    counter++;
                    continue;
                }
                if (c[i] != curr) {
                    sb.append(counter);
                    sb.append(curr);
                    curr = c[i];
                    counter = 1;
                }
                else {
                    counter++;
                }
            }
            if (curr != '.') {
                sb.append(counter);
                sb.append(curr);
            }
            return sb.toString();
        }
    }
}
tags: leetcode - string - recursion