38. Count and Say

    xiaoxiao2021-03-25  70

    题目

    原题介绍

    原题链接:https://leetcode.com/problems/count-and-say/?tab=Description 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.

    从1开始“读”这个字符串,生成下一个字符串。 1 读起来是 1个1, 即11 11读起来是2个1,即21 21读起来是1和2,1个1,即1211 1211读起来是1个1, 1个2,2个1,即111221。。。

    给出一个n,生成第n个字符串。

    思路

    从1开始模拟读这个数字串就可以了,统计同一段内相同的字符的个数,按照个数+字符输出出来,然后循环读下去就可以了。

    代码

    class Solution { public: string countAndSay(int n) { string ans = "1"; if(n == 1) return ans; for(int i = 1; i < n; ++i) { string temp; int len = ans.size(), cnt; char c; for(int j = 0; j < len; ++j) { if(!j) { c = ans[j]; cnt = 0; } if(ans[j] == c) cnt++; else { string t; while(cnt) { t += '0' + cnt % 10; cnt /= 10; } reverse(t.begin(), t.end()); temp += t; temp += c; c = ans[j]; cnt = 1; } } string t; while(cnt) { t += '0' + cnt % 10; cnt /= 10; } reverse(t.begin(), t.end()); temp += t; temp += c; ans = temp; } return ans; } };
    转载请注明原文地址: https://ju.6miu.com/read-35219.html

    最新回复(0)