您的位置:首页 > 其它

LeetCode - 38 - Count and Say

2017-08-04 14:29 387 查看
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


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 term of the count-and-say sequence.

Note: Each term of the sequence of integers will be represented as a string.

Example 1:
Input: 1
Output: "1"


Example 2:
Input: 4
Output: "1211"


很恶心,最恶心的是,题意杀!!!

第n项:第n-1项的数字串从左到右读出来。比如说第2项是11,因为第1项是1,读起来就是1个1,所以第2项的11前一个1表示后一个1的计数,以此类推。

题意明白了,就好写了。这个题目描述真的有毒啊啊啊啊啊啊啊

class Solution {
public:
string countAndSay(int n) {
if (n == 0) return "";
string s = "1";
while (--n) {
string cur = "";
for (int i = 0; i < s.length(); ++i) {
int cnt = 1;
while (i + 1 < s.length() && s[i] == s[i+1]) {
cnt++;
i++;
}
cur += to_string(cnt) + s[i];
}
s = cur;
}
return s;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: