您的位置:首页 > 其它

LeetCode 38. Count and Say

2016-04-21 09:09 190 查看
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.

I dont actually agree this is an easy one.... I made mistakes anyway....

#include <string>
#include <vector>
#include <iostream>
using namespace std;

string nextString(string tmp) {
string nextString = "";
for(int i = 0; i < tmp.size(); ++i) {
int count = 1;
while(i + 1 < tmp.size() && tmp[i] == tmp[i+1]) {
i++;
count++;
}
nextString += to_string(count) + tmp[i];
}
return nextString;
}

string countAndSay(int n) {
string tmp = "1";
for(int i = 1; i < n; ++i) {
tmp = nextString(tmp);
}
return tmp;
}

int main(void) {
cout << countAndSay(3) << endl;
}

// Second Version
string nextStringII(string tmp) {
  string res = "";
  int count = 1;
  for(int i = 1; i < tmp.size(); ++i) {
    if(tmp[i] == tmp[i-1]) {
      count++;
    } else {
      res += to_string(count) + tmp[i-1];
      count = 1;
    }
  }
  int n = tmp.size();
  if(count > 1) return res += to_string(count) + tmp[n - 1];
  return res += to_string(count) + tmp[n-1];
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: