420-报数

思路

看懂题,找到报数规律,就可以写出程序

  • n = 1,result = "1",这是初始数据
  • n = 2,result = "11",意味着上一个报数的结果是 "1个1"
  • n = 3,result = "21",意味着上一个报数的结果是 "2个1"
  • n = 4,result = "1211",意味着上一个报数的结果是 "1个2、1个1"
  • n = 5,result = "111221",意味着上一个报数的结果是 "1个1、1个2、2个1"
  • ...

code

class Solution {
public:
/*
* @param n: the nth
* @return: the nth sequence
*/
string countAndSay(int n) {
// write your code here
if (n <= 0) {
return string("");
}
string result("1");
for (int i = 1; i < n; i++) {
string temp;
int count = 1, j;
for (j = 0; j < result.size() - 1; j++) {
if (result[j] == result[j + 1]) {
count++;
}
else{
temp += ('0' + count);
temp += result[j];
count = 1;
}
}
if (j > 0 && result[j] == result[j - 1]) {
temp += ('0' + count);
temp += result[j];
}
else if (j == 0) {
temp += '1';
temp += result[j];
}
else {
temp += '1';
temp += result[j];
}
result = temp;
}
return result;
}
};
05-08 15:01