[leetcode] Count and Say
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=1时输出字符串1;n=2时,数上次字符串中的数值个数,因为上次字符串有1个1,所以输出11;n=3时,由于上次字符是11,有2个1,所 以输出21;n=4时,由于上次字符串是21,有1个2和1个1,所以输出1211。依次类推,写个countAndSay(n)函数返回字符串。
分析:将数字转换为字符串,依次统计相同字符s的个数count,然后采用 new_str = new_str + count + s的方式,组成新的字符串。
以上操作重复n-1次即可。
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 };