0%

leetcode-394

题目


题解


java版本:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public String decodeString(String s) {
Pattern pattern = Pattern.compile("(\\d+)(\\[[a-zA-Z]+])");
while (true) {
Matcher matcher = pattern.matcher(s);
if (!matcher.find()) {
break;
}
int num = Integer.parseInt(matcher.group(1));
String tmp = matcher.group(2);
String ans = tmp.repeat(num);
ans = ans.replaceAll("\\[", "");
ans = ans.replaceAll("]", "");
s = matcher.replaceFirst(ans);
}
return s;
}
}

Kotlin版本:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
fun decodeString(s: String): String {
var str = s
val pattern = Pattern.compile("(\\d+)(\\[[a-zA-Z]+])")
while (true) {
val matcher = pattern.matcher(str)
if (!matcher.find()) {
break
}
val num = matcher.group(1).toInt()
val tmp = matcher.group(2)
var ans = tmp.repeat(num)
ans = ans.replace("\\[".toRegex(), "")
ans = ans.replace("]".toRegex(), "")
str = matcher.replaceFirst(ans)
}
return str
}
}