leetcode 题解 || Count and Say 问题
来源:互联网 发布:java list<>遍历 编辑:程序博客网 时间:2024/05/23 14:04
problem:
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.
String这是一个比较有意思的题目,计数-读数-产生新字符串。注意:我刚开始的做法是把 n 先转化成 string,
再对该字符串进行计数-读数操作,
再对该字符串进行计数-读数操作,
后来发现题目已近给定初始字符串”1“,不过我还是把我的 int转换成 string部分代码帖出来了,
注释部分就是。
注释部分就是。
thinking:
(1)首先要读懂计数 - 读数的规律,比较有意思
(2)对重复的数计数,单个的数读一个什么数。
code:
class Solution {public: string countAndSay(int n) { // string start = int_to_string(n); string start ="1"; for(int i=0;i<n-1;i++ ) start = factory(start); return start; }protected: string factory(string str) { int count=1;//初始化为1 ,很巧妙 string res; if(str.empty()) return str; if(str.size()==1) { res.push_back('1'); res+=str; return res; } for(string::size_type i=0;i<str.size()-1;i++)//计数到倒数第二个 { if(str.at(i)==str.at(i+1)) { count++; if(i==str.size()-2) //到了末尾,别忘了存储 { char a=count+'0'; res.push_back(a); res.push_back(str.at(i)); } } else { char a=count+'0'; res.push_back(a); res.push_back(str.at(i)); count=1; } }//size()-1 if(str.at(str.size()-1)!=str.at(str.size()-2))//处理最后一个字符 { res.push_back('1'); res.push_back(str.at(str.size()-1)); } // factory(res,n--); return res; } /* string int_to_string(int n) // int invert into string { vector<char> array; string res; if(n<0) n=-n; while(n>0) { int a = n%10; n/=10; char b = '0'+a; array.push_back(b); } for(int i=array.size()-1;i>=0;i--) res.push_back(array.at(i)); return res; } */};
0 0
- leetcode 题解 || Count and Say 问题
- LeetCode题解:Count and Say
- LeetCode题解:Count and Say解法
- LeetCode题解——Count and Say
- LeetCode 题解(230) : Count and Say
- leetcode题解-38. Count and Say
- Leetcode题解-38. Count and Say
- Leetcode之Count and Say 问题
- LeetCode: Count and Say
- [LeetCode]Count and Say
- LeetCode Count and Say
- [Leetcode] Count and Say
- Leetcode: Count and Say
- [LeetCode] Count and Say
- LeetCode Count and Say
- [LeetCode]Count and Say
- [LeetCode] Count and Say
- LeetCode-Count and Say
- 传统B2B中小型企业如何做好全网营销
- 内存分析工具 MAT 的使用
- Android Service机制及注意点
- 438 - The Circumference of the Circle【几何】
- XMLHttpRequest 跨域问题
- leetcode 题解 || Count and Say 问题
- 2014蓝桥杯B组c/c++预赛 第九题地宫取宝 (四维线性dp)
- 一步一步理解线段树
- 踩蔗恒掩忒姿铂沈元喋瑶犴丌少眶绞撕垤摭嗍砍獾挺伎颧题懈
- DD-WRT上安装应用软件攻略
- 黑马程序员--集合
- 浔舰聋岷溟凛编际芷尺苦郛傅脑薹电奎扁汉啕凉邓骒诧石乳骜谢
- Nginx配置文件简单说明
- ios socket