-
-
Notifications
You must be signed in to change notification settings - Fork 291
Expand file tree
/
Copy path394.cpp
More file actions
80 lines (75 loc) · 2.26 KB
/
394.cpp
File metadata and controls
80 lines (75 loc) · 2.26 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
74
75
76
77
78
79
80
__________________________________________________________________________________________________
sample 4 ms submission
class Solution {
public:
string decodeString(string s) {
stack < pair<int,string> > stk;
stk.push({1,""});
int counter = 0;
for ( int i = 0; i < s.size(); i ++ )
{
char currChar = s[i];
if ( currChar == '[' )
{
stk.push( {counter, "" } );
counter = 0;
}
//if number
else if ( isdigit(currChar) )
{
counter = counter*10 + currChar - '0'; //convert to int
}
else if ( isalpha(currChar) )
{
stk.top().second += currChar;
}
else if ( currChar == ']' )
{
//got our closing bracket
pair<int,string> top = stk.top();
stk.pop();
string temp = "";
while(top.first)
{
temp = temp + top.second;
top.first--;
}
//add the string to the previous
stk.top().second += temp;
}
}
return stk.top().second;
}
};
__________________________________________________________________________________________________
sample 8704 kb submission
class Solution {
public:
string decodeString(string &s, int &i){
string ans = "";
int n = s.size();
while(i < n && s[i] != ']'){
if(isdigit(s[i])){
int number = 0;
while(s[i] <= '9' && s[i] >= '0' && i < n){
number = number * 10 + (int)s[i++] - 48;
}
++i;
string temp = decodeString(s, i);
++i;
while(number-- > 0){
ans += temp;
}
}
else{
ans += s[i++];
}
}
return ans;
}
string decodeString(string s) {
int i = 0;
return decodeString(s, i);
}
};
__________________________________________________________________________________________________