时间限制:1秒 空间限制:32768K 热度指数:3439
题目描述
The count-and-say sequence is the sequence of integers beginning as follows:
1, 11, 21, 1211, 111221, ...
1is read off as"one 1"or11.
11is read off as"two 1s"or21.
21is read off as"one 2, thenone 1"or1211.
Given an integer n, generate the n th sequence.
Note: The sequence of integers will be represented as a string.
题解:
1 #include<string> 2 #include<iostream> 3 #include<sstream> 4 #include<vector> 5 using namespace std; 6 7 class Solution { 8 public: 9 string countAndSay(int n) { 10 vector<int> arr; 11 vector<int> temp; 12 int cnt = n - 1; 13 arr.push_back(1); 14 while (cnt-- > 0) { 15 temp.clear(); 16 int count = 1; 17 for (int i = 1; i < arr.size(); i++) { 18 if (arr[i] == arr[i - 1]) { 19 count++; 20 } 21 else { 22 temp.push_back(count); 23 temp.push_back(arr[i - 1]); 24 count = 1; 25 } 26 } 27 temp.push_back(count); 28 temp.push_back(arr[arr.size() - 1]); 29 arr = temp; 30 } 31 ostringstream oss; 32 for (int i = 0; i < arr.size(); i++) { 33 oss << arr[i]; 34 } 35 return oss.str(); 36 } 37 };