Count and Say
2016-07-16 14:54
323 查看
题目描述:
The count-and-say sequence is the sequence of integers beginning as follows:
Given an integer n, generate the nth sequence.
Note: The sequence of integers will be represented as a string.
AC代码如下:
class Solution {
public:
string countAndSay(int n) {
string ans = "1";
if (n <= 0) return string();
for (int i = 0; i < n - 1; i++){
int length = ans.size();
string tmp = "";
int count = 1;
for (int j = 1; j < length; j++){
if (ans[j] == ans[j - 1]){
count++;
}
else{
char ch = ans[j - 1];
char cc = '0' + count;
tmp = tmp + cc + ch;
count = 1;
}
}
char ch = ans[length - 1];
char cc = '0' + count;
tmp = tmp + cc + ch;
ans = tmp;
}
return ans;
}
};
The count-and-say sequence is the sequence of integers beginning as follows:
1, 11, 21, 1211, 111221, ...
1is read off as
"one 1"or
11.
11is read off as
"two 1s"or
21.
21is 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.
AC代码如下:
class Solution {
public:
string countAndSay(int n) {
string ans = "1";
if (n <= 0) return string();
for (int i = 0; i < n - 1; i++){
int length = ans.size();
string tmp = "";
int count = 1;
for (int j = 1; j < length; j++){
if (ans[j] == ans[j - 1]){
count++;
}
else{
char ch = ans[j - 1];
char cc = '0' + count;
tmp = tmp + cc + ch;
count = 1;
}
}
char ch = ans[length - 1];
char cc = '0' + count;
tmp = tmp + cc + ch;
ans = tmp;
}
return ans;
}
};
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- 关于指针的一些事情
- c++ primer 第五版 笔记前言
- share_ptr的几个注意点
- Lua中调用C++函数示例
- Lua教程(一):在C++中嵌入Lua脚本
- Lua教程(二):C++和Lua相互传递数据示例
- C++联合体转换成C#结构的实现方法
- C++高级程序员成长之路
- C++编写简单的打靶游戏
- C++ 自定义控件的移植问题
- C++变位词问题分析
- C/C++数据对齐详细解析
- C++基于栈实现铁轨问题
- C++中引用的使用总结
- 使用Lua来扩展C++程序的方法
- C++中调用Lua函数实例
- Lua和C++的通信流程代码实例
- C++的template模板中class与typename关键字的区别分析
- C与C++之间相互调用实例方法讲解