Sunday, February 4, 2018

[2018-Interview] Count and Say

Original question: https://leetcode.com/problems/count-and-say/description/

My answer: Recursive solution.




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


No comments:

Post a Comment