38. 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.
说真的刚开始真不知道这道题要干什么,英语有点差~~~
当明白是什么意思的时候又发现描述起来有点问题,语文有点差~~~
生硬的描述一下吧:1被读作“1个1” 或 11;11被读作“2个1”或21;21被读作“1个2,1个1”或1211;依次这样下去,输出第n个序列。
代码如下:
1 class Solution { 2 public: 3 string countAndSay(int n) { 4 string first = "1"; 5 for(int i = 1; i < n; i++) 6 { 7 string ss = ""; 8 int count = 1; 9 for(int j = 1; j < first.length(); j++) 10 { 11 if(first[j-1] == first[j]) 12 { 13 count ++; 14 } 15 else 16 { 17 ss = ss + (char)(count + ‘0‘) + first[j-1]; 18 count = 1; 19 } 20 } 21 first = ss + (char)(count + ‘0‘) + first[first.length()-1]; 22 } 23 return first; 24 } 25 };
时间: 2024-10-09 04:16:58