美文网首页
38. Count and Say

38. Count and Say

作者: SilentDawn | 来源:发表于2018-05-28 10:30 被阅读0次

Problem

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

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

Input: 1
Output: "1"
Input: 4
Output: "1211"

Code

static int var = [](){
    std::ios::sync_with_stdio(false);
    cin.tie(NULL);
    return 0;
}();
class Solution {
public:
    string countAndSay(int n) {
        string str = "1";        
        if(n==1)
            return str;
        string tar = "";        
        for (int i = 0; i<n - 1; i++) {
            int count = 0;
            char tmp = str[0];
            for (int j = 0; j<str.size(); j++) {
                if (str[j] == tmp)
                    count++;
                else {
                    tar += to_string(count) + tmp;
                    count = 1;
                    tmp = str[j];
                }
            }
            tar += to_string(count) + tmp;
            str = tar;
            tar = "";
        }
        return str;
    }
};

Result

38. Count and Say.png

相关文章

网友评论

      本文标题:38. Count and Say

      本文链接:https://www.haomeiwen.com/subject/iwswjftx.html