标签:
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.
1 class Solution 2 { 3 private: 4 string IntToString(int n) 5 { 6 if(n==0) 7 return "0"; 8 9 string str = ""; 10 while(n>0) 11 { 12 str.insert(str.begin(), n % 10 + ‘0‘); 13 n /= 10; 14 } 15 return str; 16 } 17 18 public: 19 string countAndSay(int n) 20 { 21 if(n == 1) 22 return "1"; 23 24 if(n == 2) 25 return "11"; 26 27 int i=0 ,j=0; 28 29 string temp = "11", str = ""; 30 for(i=3; i<=n; i++) 31 { 32 int count = 1; 33 str = ""; 34 for(j=1; j<temp.size(); j++) 35 { 36 if(temp[j] == temp[j-1]) 37 count++; 38 else 39 { 40 str = str + IntToString(count) + temp[j-1]; 41 count = 1; 42 } 43 if(j == temp.size()-1) 44 str = str + IntToString(count) + temp[j]; 45 } 46 temp = str; 47 } 48 49 return str; 50 } 51 };
标签:
原文地址:http://www.cnblogs.com/lxd2502/p/4254338.html