-
-
Notifications
You must be signed in to change notification settings - Fork 298
/
Copy path38.cpp
130 lines (128 loc) · 3.54 KB
/
38.cpp
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
__________________________________________________________________________________________________
4ms
class Solution {
public:
string countAndSay(int n) {
int count = 1;
string tmp, result = "1";
for (int i = 1; i < n; i++) {
tmp = result + 'x';
result = "";
for (int j = 1; j < tmp.size(); j++) {
if (tmp[j] == tmp[j - 1]) {
count++;
} else {
result += '0' + count;
result += tmp[j - 1];
count = 1;
}
}
}
return result;
}
};
__________________________________________________________________________________________________
8ms
class Solution {
public:
string countAndSay(int n) {
if (n<1) return "";
string res = "1";
while(--n)
{
string cur = "";
for (int i = 0; i < res.size(); i++)
{
int cnt = 1;
while(i+1 < res.size() && res[i] == res[i+1])
{
cnt++;
i++;
}
cur += to_string(cnt) + res[i];
}
res = cur;
}
return res;
}
};
__________________________________________________________________________________________________
12ms
class Solution {
public:
string countAndSay(int n) {
int count = 1;
string result = "1x";
for (int i = 1; i < n; i++) {
for (int j = 1; j < result.size(); j++) {
if (result[j] == result[j - 1]) {
count++;
} else {
result.replace(j - count, count - 1, 1, '0' + count);
j -= count - 2;
count = 1;
}
}
}
result.resize(result.size() - 1);
return result;
}
};
__________________________________________________________________________________________________
8512 kb
class Solution {
public:
string countAndSay(int n) {
string start="1";
int k=1;
while(k<n)
{
string tem="";
char temc=start[0];
int count=1;
for(int i=1;i<start.size();i++)
{
if(start[i]==temc)
{
count++;
}
if(start[i]!=temc)
{
tem.push_back(count+'0');
tem.push_back(temc);
temc=start[i];
count=1;
}
}
tem.push_back(count+'0');
tem.push_back(temc);
start=tem;
k++;
}
return start;
}
};
__________________________________________________________________________________________________
8524 kb
class Solution {
public:
string countAndSay(int n) {
string prestr = "1";
string str;
if (n == 1) return prestr;
for (int i=2; i <= n; i++){
int count = 0;
for (int j = 0; j < prestr.size(); j++){
count++;
if (j+1 < prestr.size() && prestr[j] == prestr[j+1]) continue;
str.push_back('0' + count);
str.push_back(prestr[j]);
count = 0;
}
prestr = str;
str.clear();
}
return prestr;
}
};
__________________________________________________________________________________________________