【leetcode】38. Count and Say 数字转换

1. 题目

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.

2. 思路

迭代重复即可

3. 代码

耗时:3ms

#include <sstream>

class Solution {
public:
    string countAndSay(int n) {
        string s = "1";
        while (--n != 0) {
            s = foo(s);
        }
        return s;
    }
    
    string foo(string& s) {
        string ret;
        int len = s.length();
        if (len == 0) {return ret;}
        char last = s[0];
        int cnt = 1;
        stringstream ss;
        for (int i = 1; i < len; i++) {
            if (s[i] != last) {
                ss << cnt << last;
                last = s[i];
                cnt = 1;
            } else {
                cnt++;
            }
        }
        ss << cnt << last;
        return ss.str();
    }
};
    原文作者:knzeus
    原文地址: https://segmentfault.com/a/1190000007300223
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞