-
Notifications
You must be signed in to change notification settings - Fork 0
/
DecodeString.scala
48 lines (43 loc) · 1.14 KB
/
DecodeString.scala
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
package DecodeString
/**
* Created by iodone on {19-11-14}.
*/
/**
* 解题报告
*
* 思路:递归思路。分为三块expr = [a-z]*\[expr\](0,n)expr
*/
object Solution {
def decodeString(s: String): String = {
if (s == "") ""
else if (s.head >= 'A' && s.head <= 'z') s.head +: decodeString(s.tail)
else {
val xs = s.split('[')
val replicate = xs.head.toInt
val left = xs.tail.mkString("[")
val (body, tail) = splitString(left)
(decodeString(body) * replicate) ++ decodeString(tail)
}
}
// input string like this: aaa2[b]cc]
def splitString(s: String): (String, String) = {
var sum = 1
var splitPoinit = 0
for (i <- 0 until s.length) {
if (sum > 0) {
if (s(i) == ']') {
sum -= 1
if (sum == 0) splitPoinit = i
}
else if (s(i) == '[') sum += 1
}
}
(s.substring(0, splitPoinit), s.substring(splitPoinit+1))
}
def main(args: Array[String]): Unit = {
println(splitString("aaa2[b]cc]ddd"))
println(decodeString("3[a]2[bc]"))
println(decodeString("3[a2[c]]"))
println(decodeString("2[abc]3[cd]ef"))
}
}