1. 程式人生 > >Count and Say問題及解法

Count and Say問題及解法

問題描述:

The count-and-say sequence is the sequence of integers beginning as follows:
1, 11, 21, 1211, 111221, ...

1is read off as"one 1"or11.
11is read off as"two 1s"or21.
21is read off as"one 2, thenone 1"or1211.

Given an integern, generate thenthsequence.

Note: The sequence of integers will be represented as a string.

問題分析:

 題意是n=1時輸出字串1;n=2時,數上次字串中的數值個數,因為上次字串有1個1,所以輸出11;n=3時,由於上次字元是11,有2個1,所以輸出21;n=4時,由於上次字串是21,有1個2和1個1,所以輸出1211依次類推。

過程詳見程式碼:

class Solution {
public:
    string countAndSay(int n) {
        if(n <= 0) return "";
        string say = "1";
        for(int i = 1;i < n;i++)
        {
        	int count = 0;
    		char last = say[0];
    		stringstream ss;
        	for(int j = 0;j < say.length();j++)
        	{
        		if(say[j] == last) count++;
        		else
        		{
        			ss << count << last;
        			count = 1;
        			last = say[j];
				}
			}
			ss << count << last;
			say = ss.str();
		}
		return say;
    }
};