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 n
th sequence.
Notice
The sequence of integers will be represented as a string.
Given n = 5
, return "111221"
.
LeetCode上的原题,请参见我之前的博客Count and Say。
class Solution { public: /** * @param n the nth * @return the nth sequence */ string countAndSay(int n) { if (n < 1) return ""; string res = "1"; while (--n) { res.push_back('#'); string t = ""; int cnt = 1; for (int i = 1; i < res.size(); ++i) { if (res[i] == res[i - 1]) ++cnt; else { t += to_string(cnt) + res[i - 1]; cnt = 1; } } res = t; } return res; } };
本文转自博客园Grandyang的博客,原文链接:计数和读法[LintCode] Count and Say ,如需转载请自行联系原博主。