LeetCode 38. Count and Say

来源:互联网 发布:sql中建立表的命令是 编辑:程序博客网 时间:2024/05/22 17:06

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 Versionstring 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];}


0 0
原创粉丝点击