leetcode - Count and Say
Q:
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.
1 class Solution { 2 public: 3 string countAndSay(int n) { 4 int count=1; 5 string seq, result; 6 if(n==1){ 7 return "1"; 8 } 9 // if(n==2){ 10 // return "11"; 11 // } 12 seq = countAndSay(n-1); 13 string::iterator iter_seq = seq.begin()+1; 14 while(iter_seq!=seq.end()){ 15 if (*iter_seq == *(iter_seq-1)){ 16 count++; 17 iter_seq++; 18 } 19 else{ 20 result.push_back(‘0‘+count); 21 result.push_back(*(iter_seq-1)); 22 count=1; 23 iter_seq++; 24 } 25 } 26 result.push_back(‘0‘+count); 27 result.push_back(*(iter_seq-1)); 28 return result; 29 } 30 };
我的思路: 递归。
比较简单。 要注意如何将数字转化为char, push_back只接受char
http://blog.csdn.net/talentluke/article/details/6050617
http://zhidao.baidu.com/link?url=i4aEJh3bn_QWQC-DyXjF3eEorCMklZiEWGg2u8N8MdPl4-HkKQIvL8FazbX7UeRhK3WetF-XXCctpm5ElYHXaa
原文:http://www.cnblogs.com/shnj/p/4464458.html