【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;}

0 0