LeetCode 38:Count and Say
2015-12-23 15:09
295 查看
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.
"数和说"序列的开头如下:
1, 11, 21, 1211, 111221, ...
1 读作"一个1" 或者11 (1个1)
11 读作"两个1" 或者21 (2个1)
21 读作"一个2,然后是一个1" 或者1211 (1个2,1个1)
给定一个整数n,返回第n个"数和说"序列
注意:返回的整数序列应当作用一个字符串表示
第一次写出一次通过的代码。。。虽然是很简单的题目但还是很高兴←_←思路就是从左往右读,读到不一样的就记录前面读到的个数和数字,然后接着读。。。
class Solution {
public:
string countAndSay(int n) {
string temp="1";
for(int i=1;i<n;i++)
{
string temp1;
int num=temp[0]-'0';
int count=0;
for(int j=0;j<temp.length();j++)
{
if(temp[j]-'0'==num)
count++;
else
{
temp1.append(to_string(count));
temp1.push_back(num+'0');
num=temp[j]-'0';
count=1;
}
}
temp1.append(to_string(count));
temp1.push_back(num+'0');
temp=temp1;
}
return temp;
}
};
1, 11, 21, 1211, 111221, ...
1is read off as
"one 1"or
11.
11is read off as
"two 1"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.
"数和说"序列的开头如下:
1, 11, 21, 1211, 111221, ...
1 读作"一个1" 或者11 (1个1)
11 读作"两个1" 或者21 (2个1)
21 读作"一个2,然后是一个1" 或者1211 (1个2,1个1)
给定一个整数n,返回第n个"数和说"序列
注意:返回的整数序列应当作用一个字符串表示
第一次写出一次通过的代码。。。虽然是很简单的题目但还是很高兴←_←思路就是从左往右读,读到不一样的就记录前面读到的个数和数字,然后接着读。。。
class Solution {
public:
string countAndSay(int n) {
string temp="1";
for(int i=1;i<n;i++)
{
string temp1;
int num=temp[0]-'0';
int count=0;
for(int j=0;j<temp.length();j++)
{
if(temp[j]-'0'==num)
count++;
else
{
temp1.append(to_string(count));
temp1.push_back(num+'0');
num=temp[j]-'0';
count=1;
}
}
temp1.append(to_string(count));
temp1.push_back(num+'0');
temp=temp1;
}
return temp;
}
};
相关文章推荐
- Android编译系统参考手册
- 手机自动化测试:Appium源码分析之跟踪代码分析一 1
- Summernote
- 类别(Categories)和扩展/匿名类别(extensions)及其延伸使用
- django常用函数
- 设计模式C++实现--状态模式
- 常见的块状元素与内联元素
- [程序设计语言-实践之路]读书笔记(1)
- stay hungry ,stay foolish!
- 云计算推动互联网金融技术性变革 打造专业安全的金融解决方案
- asp.net文件压缩,下载,物理路径,相对路径,删除文件
- 存储过程实现报表数据源的利弊分析
- 如何获取(GET)一杯咖啡——星巴克REST案例分析
- 第九章-----jsp标签
- 线上引流压测工具Meteor
- 手机自动化测试:Appium源码之API(2)
- Java数据结构和算法系列1--链表
- Xcode中使用Git进行代码版本控制
- Hibernate 参数设置一览表
- JVM内存区域