38. Count and Say

The count-and-say sequence is the sequence of integers with the first five terms as following:

1.     1
2.     11
3.     21
4.     1211
5.     111221

1 is read off as "one 1" or 11.
11 is read off as "two 1s" or 21.
21 is read off as "one 2, then one 1" or 1211.

Given an integer n, generate the nth term of the count-and-say sequence.

Note: Each term of the sequence of integers will be represented as a string.

Example 1:

Input: 1
Output: "1"

Example 2:

Input: 4
Output: "1211"

Solution

(1) Java

class Solution {
    public String countAndSay(int n) {
        String rst = "1";
        while (n > 1) {
            n--;
            int count = 0;
            StringBuilder sb = new StringBuilder();
            char[] ca = rst.toCharArray();
            for (int i = 0; i < ca.length; i++) {
                if (i == 0) {
                    count = 1;
                } else if (ca[i] != ca[i-1]) {
                    sb.append(count).append(ca[i-1]);
                    count = 1;
                } else {
                    count++;
                }
            }
            sb.append(count).append(ca[ca.length-1]);
            rst = sb.toString();
        }
        return rst;
    }
}

(2) Python

class Solution:
    def countAndSay(self, n):
        """
        :type n: int
        :rtype: str
        """
        rst = '1'
        while n > 1:
            n -= 1
            tmp = ''
            count = 0
            for i, c in enumerate(rst):
                if i == 0:
                    count = 1
                elif c != rst[i-1]:
                    tmp = tmp + str(count) + rst[i-1]
                    count = 1
                elif c == rst[i-1]:
                    count += 1
            tmp = tmp + str(count) + rst[len(rst)-1]
            rst = tmp
        return rst

(3) Scala



results matching ""

    No results matching ""