leetcode -- Count and Say

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.

---------------------------------------------------------------------------------------

思路:遞歸。顯然知道 n = k時的序列,很容易得到n=k+1的序列。遞歸出口n=1即可。

class Solution {
public:
    string countAndSay(int n) {
    	string ret;
    	if(n == 1){   //遞歸出口
    		ret.append(1, '1');
    		return ret;
    	}
		string pre = countAndSay(n - 1);
		ret = countNext(pre);
		return ret;
    }
    string countNext(string s){
    	int count = 1;
    	string ret;
    	for(string::size_type ix = 0; ix < s.size(); ix++){
    		if(ix + 1 < s.size() && s[ix] == s[ix + 1]){
    			count++;
    			continue;
    		}
			ret.append(1, '0' + count);
			ret.append(1, s[ix]);
			count = 1;
	}
    	return ret;
    }
};


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