Skip to content

Commit ef0fa16

Browse files
committed
394. Decode String
1 parent d09d906 commit ef0fa16

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
object Solution {
2+
def decodeString(s: String): String = {
3+
val stack = scala.collection.mutable.Stack.empty[String]
4+
for (c <- s) {
5+
if (c != ']') {
6+
stack.push(c.toString)
7+
} else {
8+
var s = ""
9+
while (stack.top != "[") {
10+
s += stack.pop()
11+
}
12+
stack.pop()
13+
var n = ""
14+
while (stack.nonEmpty && stack.top.toIntOption.nonEmpty) {
15+
n = stack.pop() + n
16+
}
17+
stack.push(s * n.toInt)
18+
}
19+
}
20+
stack.mkString.reverse
21+
}
22+
}
23+
24+
25+
Solution.decodeString("3[a]2[bc]") // "aaabcbc"
26+
Solution.decodeString("3[a2[c]]") // "accaccacc"
27+
Solution.decodeString("2[abc]3[cd]ef") // "abcabccdcdcdef"
28+

0 commit comments

Comments
 (0)