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.
http://www.lintcode.com/en/problem/count-and-say/
Discussion
题目不难,理解题目难,其实就是把数数出来。。。比如322555 --> 一个3两个2三个5 -->132235. 所以就是count连续出现的次数,再组成新的string
Solution
class Solution {
public:
/**
* @param n the nth
* @return the nth sequence
*/
string countAndSay(int n) {
// Write your code here
string result;
if(n<=0) return result;
result = "1";
for(int i=2; i<=n; i++) {
result = countAndSay(result);
}
return result;
}
private:
string countAndSay(string nums) {
int count = 1;
int n = nums.length();
string result="";
for(int i=0; i<n; i++) {
if(i<n-1 && nums[i] == nums[i+1]) {
count++;
continue;
}
result += to_string(count);
result += nums[i];
count = 1;
}
return result;
}
};
找错误
class Solution {
public:
/**
* @param n the nth
* @return the nth sequence
*/
string countAndSay(int n) {
// Write your code here
string result;
if(n<=0) return result;
result = "1";
for(int i=2; i<=n; i++) {
result = countAndSay(result);
}
return result;
}
private:
string countAndSay(string nums) {
int count = 1;
int n = nums.length();
string result="";
for(int i=1; i<n; i++) {
if(nums[i] == nums[i-1]) {
count++;
continue;
}
result += to_string(count)+nums[i-1];
count = 1;
}
return result;
}
};