【leetcode】38. Count and Say
来源:互联网 发布:问卷星快速录入数据 编辑:程序博客网 时间:2024/05/20 23:35
一、题目描述
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.
题目解读:听读序列:1,11,21,1211,111221,....
第一个数字是1,1个1所以第二数字是11,2个1所以第三个数字是21,1个2和1个1所以第四个数字是1211.... 按这种规律类推
思路:从第三个开始,从1~n-1,对每个数字计数。每次都与前一个进行比较,相同就计数+1,否则就先把前一个数的个数+值存入结果字符串中。
c++代码(20ms,1.11%)
class Solution {public: string countAndSay(int n) { string s="11"; if(n==1) return "1"; if(n==2) return "11"; for(int i=2;i<n;i++){ string str=""; for(int j=1;j<s.size();j++){ int count=1; while(s[j] == s[j-1] && j<s.size()){ count++; j++; } stringstream ss,cc; ss<<count; cc<<s[j-1]; str+=ss.str()+cc.str(); if(j==(s.size()-1) && s[j]!=s[j-1]){ int i=1; stringstream mm,nn; mm<<i; nn<<s[j]; str+=mm.str()+nn.str(); } }//for s=str; } return s; }};
0 0
- [LeetCode]38.Count and Say
- LeetCode --- 38. Count and Say
- LeetCode 38.Count and Say
- [Leetcode] 38. Count and Say
- 38. Count and Say LeetCode
- Leetcode 38. Count and Say
- leetcode 38. Count and Say
- [leetcode] 38. Count and Say
- LeetCode-38.Count and Say
- LeetCode *** 38. Count and Say
- leetcode 38. Count and Say
- LeetCode-38. Count and Say
- LeetCode 38. Count and Say
- LeetCode 38. Count and Say
- Leetcode - 38. Count and Say
- LeetCode 38. Count and Say
- Leetcode 38. Count and Say
- LeetCode 38. Count and Say
- 构造函数和析构函数及其作用
- Java之跨平台性原理以及JRE与JDK笔记
- Android实现ScrollView动态显示文字
- [疯狂Java]面向对象:常量池、equals标准模板
- html标签简单总结
- 【leetcode】38. Count and Say
- session、cookie与“记住我的登录状态”的功能的实现
- 关于字符串那点事(一)
- javac 和 java命令
- 子墨子游公尚过于越
- FFmpeg常用基本命令
- 线性表的顺序存储结构
- acm之递归题目3
- HADOOP基本操作命令