February 13, 2019

38. Count and Say

38. Count and Say

Java:

class Solution {
    public String countAndSay(int n) {
        String str = "1";
        for (int i = 0; i < n - 1; i++) {
            StringBuilder sb = new StringBuilder();
            int count = 0;
            int prev = 0;
            for (int j = 0; j < str.length(); j++) {
                int cur = str.charAt(j) - '0';
                if (j == 0 || cur == prev) {
                    count++;
                } else {
                    sb.append(count);
                    sb.append(prev);
                    count = 1;
                }
                prev = cur;
            }
            sb.append(count);
            sb.append(prev);
            str = sb.toString();
        }
        return str;
    }
}

Python:

class Solution:
    def countAndSay(self, n: 'int') -> 'str':
        res = "1"
        for i in range(1, n):
            next_res = ""
            prev = ""
            count = 0
            for j in range(len(res)):
                cur = res[j]
                if j == 0 or cur == prev:
                    count += 1
                else:
                    next_res += str(count)
                    next_res += prev
                    count = 1
                prev = cur
            next_res += str(count)
            next_res += prev
            res = next_res

        return res
comments powered by Disqus