关闭

Leetcode 38. Count and Say

71人阅读 评论(0) 收藏 举报
分类:

The count-and-say sequence is the sequence of integers beginning as follows:
1, 11, 21, 1211, 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 sequence.

Note: The sequence of integers will be represented as a string.

class Solution {
public:
    string countAndSay(int n) {
        if(n==1) return "1"; // base case
        string res,tmp = countAndSay(n-1); // recursion
        char c= tmp[0];
        int count=1;
        for(int i=1;i<tmp.size();i++)
            if(tmp[i]==c)
                count++;
            else {
                res+=to_string(count);
                res.push_back(c);   //res.push_back(c)的效果就是字符串拼接,相当于 res+=c ,两条语句合并可写为:res=res+to_string(count)+c;
                c=tmp[i];
                count=1;
            }
        res+=to_string(count);
        res.push_back(c);
        return res;
    }
};
0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:12929次
    • 积分:1025
    • 等级:
    • 排名:千里之外
    • 原创:94篇
    • 转载:7篇
    • 译文:0篇
    • 评论:0条