-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path394.decode-string.cpp
More file actions
100 lines (97 loc) · 2.14 KB
/
394.decode-string.cpp
File metadata and controls
100 lines (97 loc) · 2.14 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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
/*
* @lc app=leetcode id=394 lang=cpp
*
* [394] Decode String
*/
// @lc code=start
#include <vector>
#include <sstream>
#include <string>
using namespace std;
class Solution
{
public:
char read_char(string &s, int sp)
{
if (s.length() > sp)
{
return s[sp];
}
return -1;
}
string decodeString(string s)
{
return f(s, 0, s.length());
}
string f(string &s, int sp, int se)
{
int mul = 0;
string tmp = "";
stringstream ss = stringstream();
while (1)
{
if (sp == se)
{
break;
}
char c = read_char(s, sp);
if (c == -1)
{
break;
}
sp++;
if (c >= 'a' && c <= 'z')
{
ss << c;
}
else if (c >= '0' && c <= '9')
{
int num = c - '0';
while (1)
{
char c = read_char(s, sp);
sp++;
if (!(c >= '0' && c <= '9'))
{
sp--;
break;
}
num = num * 10 + c - '0';
}
mul = num;
}
else if (c == '[')
{
int o_sp = sp;
int l_cnt = 1;
while (char c = read_char(s, sp))
{
sp++;
if (c == '[')
{
l_cnt++;
}
else if (c == ']')
{
l_cnt--;
}
if (l_cnt == 0)
{
break;
}
}
tmp = f(s, o_sp, sp - 1);
while (mul--)
{
ss << tmp;
}
}
else
{
exit(-1);
}
}
return ss.str();
}
};
// @lc code=end