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 string str = int2string(n); 5 int len = str.length(); 6 if(len == 0) return NULL; 7 if(len == 1) return str; 8 9 string result; 10 int count = 1; 11 for(int i = 1; i < len; i++){ 12 if(str[i-1] == str[i]) count++; 13 else{ 14 result = result + int2string(count) + str[i-1]; 15 count = 1; 16 } 17 if(i == len - 1) result = result + int2string(count) + str[i]; 18 } 19 return result; 20 } 21 string int2string(int n){ 22 string s; 23 while(n){ 24 s += n % 10 + '0'; 25 n /= 10; 26 } 27 reverse(s.begin(), s.end()); 28 return s; 29 } 30 };
然后老是不通过,翻了别人的解题思路,才知道是什么意思 0.0
题目意思为 第一个序列为1;由于1已经表示为1了,所以第二个序列为Count-And-Say第一个序列的结果,为11;同理第三个序列为Count-And-Say第二个序列的结果,为21;第四个序列为1211……
代码如下:
1 class Solution { 2 public: 3 string countAndSay(int n) { 4 if(n == 1) return "1"; 5 string result = "1"; 6 for(int i = 1; i < n; i++){ 7 result = convert(result); 8 } 9 return result; 10 } 11 string convert(string str){ 12 int len = str.length(); 13 if(len == 1) return "1" + str; 14 string result; 15 int count = 1; 16 for(int i = 1; i < len; i++){ 17 if(str[i-1] == str[i]) count++; 18 else{ 19 result = result + static_cast<char>(count + '0') + str[i-1]; 20 count = 1; 21 } 22 if(i == len - 1) result = result + static_cast<char>(count + '0') + str[i]; 23 } 24 return result; 25 } 26 };