您的位置:首页 > 其它

【LeetCode】Count and Say

2014-06-10 21:45 465 查看
题目描述:

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.
一开始考虑会不会出现统计大于9的情况,懒得自己写int转string,就想用itoa,提交了下发现CE,索性就忽略这种情况直接提交吧,果然过了……看了下test case只有18个。
没什么难点,就是统计下重复元素的个数,用s[i-1]==s[i]可以很方便的判定。

代码如下:

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