【leetcode c++】38 Count and Say
来源:互联网 发布:域名商 编辑:程序博客网 时间:2024/05/22 17:09
Count and Say
The count-and-say sequence is the sequenceof 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 one1" or 1211.
Given an integer n, generate the nthsequence.
Note: The sequence of integers will berepresented as a string.
这道题首先要读懂,首先,读法都能理解了,一串数字,从左到右数数字。21读成1个2、1个1,然后数字表示成1211。长一点的比如111221读成3个1、2个2、1个1。数字表示312211。然后,这些数字怎么来呢?1, 11, 21, 1211,111221, ...
首先规定,第一个是1;第二个数字就是第一个的读法;第三个数字就是第二个数字的读法;第四个数字就是第三个数字的读法……
是不是要一发递归?→ →
瞄了一眼函数头。stringcountAndSay(int n)。输入是int,输出是string。看来不打算给我们递归了。当然也可以重新写一个新函数,然后调用。
这里就不递归了。我们用个中间值string来传递好了。
其实我解题本质就是,用循环来实现递归而已。没递归漂亮。
Leetcode的AcceptedSolutions Runtime Distribution(15-06-10)
源码:(VS2013)
#include <iostream>#include <sstream>#include <map>#include <vector>using namespace std;string countAndSay(int n);int main(){cout << countAndSay(5);return 0;}string countAndSay(int n){if (1 == n){return "1";}string s;//intתstringstringstream ss;string tempString = "";char tempChar;string tempRes = "1";int myCount = 0;for (int i = 2; i <= n;i++){tempString = tempRes;tempRes = "";string::iterator iter = tempString.begin();tempChar = *iter;while (iter != tempString.end()){if (tempChar == *iter){myCount++;}else{ss << myCount;ss >> s;//intתstringtempRes += s;tempRes += tempChar;ss.clear();//21tempChar = *iter;myCount = 1;}iter++;}ss << myCount;ss >> s;//intתstringtempRes += s;iter--;tempRes += *iter;ss.clear();myCount = 0;}return tempRes;}
- 【leetcode c++】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
- 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
- codeforces #309 553C C. Love Triangles(dfs+ 图论)
- swift初体验
- iOS学习笔记 数据库操作(使用FMDB)
- 关于使用 MongoDB Connector for Hadoop 的经验和教训
- 18-m-4Sum
- 【leetcode c++】38 Count and Say
- android adt 最新下载地址23.03
- 回归.Net
- 20150623 javascript实现的简单刷贴
- Fire Game
- 在linux下,解决不能输入也不能退出的问题
- 【软件测试】2、软件测试的概念和基本原则
- JavaSE笔记之<final关键字>
- Intent的Component,Action和Category属性详解-android学习之旅(五十)