【leetcode c++】38 Count and Say

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תstring
	stringstream 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תstring
				tempRes += s;
				tempRes += tempChar;
				ss.clear();
				//21
				tempChar = *iter;
				myCount = 1;
			}
			iter++;
		}
		ss << myCount;
		ss >> s;//intתstring
		tempRes += s;
		iter--;
		tempRes += *iter;
		ss.clear();

		myCount = 0;
	}

	return tempRes;
}

發佈了44 篇原創文章 · 獲贊 4 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章