-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDecode String.cs
More file actions
29 lines (28 loc) · 909 Bytes
/
Decode String.cs
File metadata and controls
29 lines (28 loc) · 909 Bytes
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
public class Solution {
public string DecodeString(string s) {
var nums = new Stack<int>();
var strs = new Stack<StringBuilder>();
var cnt = 0;
var sb = new StringBuilder();
foreach (var ch in s.ToCharArray()) {
if (ch >= '0' && ch <= '9') {
cnt = 10 * cnt + ch - '0';
} else if (ch == '[') {
nums.Push(cnt);
strs.Push(sb);
cnt = 0;
sb = new StringBuilder();
} else if (ch == ']') {
var k = nums.Pop();
var cur = strs.Pop();
for (var i = 0; i < k; i++) {
cur.Append(sb);
}
sb = cur;
} else {
sb.Append(ch);
}
}
return strs.Count == 0 ? sb.ToString() : strs.Peek().ToString();
}
}