Count and Say

Problem: Count and Say

Just use the brute-force method then we can solve the problem.

Code in Python:

class Solution(object):
    def countAndSay(self, n):
        """
        :type n: int
        :rtype: str
        """
        ans = "1"
        for i in xrange(1, n):
            num, cur, count = "", "", 0
            for c in ans:
                if c != num:
                    if count: cur += str(count) + num
                    num, count = c, 1
                else:
                    count += 1
            ans = cur + str(count) + num
        return ans

Code in Java:

public class Solution {
    public String countAndSay(int n) {
        String res = "1";
        for (int i = 2; i <= n; i++) {
            String current = "";
            int count = 0;
            char digit = '.';
            for (int j = 0; j < res.length(); j++) {
                if (res.charAt(j) != digit) {
                    if (digit != '.') {
                        current += Integer.toString(count) + String.valueOf(digit);
                    }
                    digit = res.charAt(j);
                    count = 1;
                } else {
                    count++;
                }
            }
            current += Integer.toString(count) + String.valueOf(digit);
            res = current;
        }
        return res;
    }
}

results matching ""

    No results matching ""