-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCountAndSay.cpp
More file actions
executable file
·73 lines (63 loc) · 1.58 KB
/
CountAndSay.cpp
File metadata and controls
executable file
·73 lines (63 loc) · 1.58 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
//
// CountAndSay.cpp
// leetcode
//
// Created by witwolf on 4/28/15.
// Copyright (c) 2015 witwolf. All rights reserved.
//
#include <iostream>
#include <vector>
#include <utility>
#include <string>
#include <time.h>
using namespace std;
class Solution {
public:
string countAndSay(int n) {
if(n == 1){
return "1";
}
string result;
vector<pair<int,int> > v;
v.push_back(make_pair(1, 1));
vector<pair<int,int> > vtemp;
while (--n > 1) {
vtemp.clear();
for(int i = 0; i < v.size(); ++i){
push(vtemp,v[i]);
}
v = vtemp;
}
for(int i = v.size() -1 ; i >=0; --i){
const pair<int,int> &p = v[i];
result.push_back(p.first + '0');
result.push_back(p.second + '0');
}
return result;
}
void push(vector<pair<int,int> > &v,pair<int,int> &p){
// second
if(!v.empty() && v.back().second == p.second){
v.back().first += 1;
}else{
v.push_back(make_pair(1, p.second));
}
// first
if(v.back().second == p.first){
v.back().first += 1;
}else{
v.push_back(make_pair(1, p.first));
}
}
};
int main(int argc,char **argv){
Solution s;
time_t start = time(NULL);
time_t end;
for(int i = 20 ;i <= 100 ; ++i){
s.countAndSay(i);
end = time(NULL);
cout << "cost " << end - start << " seconds to count " << i << endl;
start = end;
}
}