leetcode 38. 外觀數列 「外觀數列」是一個整數序列,從數字 1 開始,序列中的每一項都是對前一項的描述。前五項如下

1、思路:

     從1開始遍歷,求出後面每一個轉化後的數。依次求下一個。

string countAndSay(int n) {
	string res = "1";
	for (int i = 2; i <= n; i++) {
		string tempStr;
		for (int j = 0; j < res.size(); j++) {
			char ch = res[j];
			int count = 1;
			while (j < res.size() - 1 && ch == res[j + 1]) {
				count++;
				j++;
			}
			tempStr.push_back(count + '0');
			tempStr.push_back(ch);
		}
		res = tempStr;
	}
	return res;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章