問題:
Given an encoded string, return it's decoded string.
The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times. Note that k is guaranteed to be a positive integer.
You may assume that the input string is always valid; No extra white spaces, square brackets are well-formed, etc.
Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, k. For example, there won't be input like 3a or 2[4].
Examples:s = "3[a]2[bc]", return "aaabcbc".
s = "3[a2[c]]", return "accaccacc".
s = "2[abc]3[cd]ef", return "abcabccdcdcdef".
大意:
給出一個編碼了的字符串,返回它的解碼字符串。
編碼規則是:k[編碼字符串],方括號里的編碼字符串會重復k次。注意k保證是一個正整數。
你可以假設輸入的字符串都是有效的;沒有額外的空格,方括號是能夠匹配的,等等。
此外,你可以假設原始數據不包含任何數字,數字只用來表示重復次數k。比如,不會有 3a 或者 2[4] 這樣的輸入。
例子:s = "3[a]2[bc]", return "aaabcbc".
s = "3[a2[c]]", return "accaccacc".
s = "2[abc]3[cd]ef", return "abcabccdcdcdef".
思路:
這個思路比較直,遍歷字符串,遇到數字后,記錄下數字,獲取方括號內的字符串,重復k次添加到結果字符串中。
需要注意的有兩個地方,一個是方括號中可能嵌套重復的內容,所以一是要準確找到左括號對應的右括號是哪個,我們用一個變量來記錄遇到的左括號和右括號數量就可以了,二是要用遞歸來操作內容的重復,因為里面還可能包含著重復的內容需要解碼。另一個要注意的是數字不一定是一位數,還可能是多位數,因此當遇到數字后,要看看后面是不是還是數字,是的話要記錄下來換算成真正的重復次數。
public class Solution {
public String decodeString(String s) {
return decodeSub(s, 1);
}
public String decodeSub(String sub, int count) {
String trueStr = "";
for (int i = 0; i < sub.length(); i++) {
if (sub.charAt(i) - '1' >= 0 && sub.charAt(i) - '9' <= 0) {
int subCount = sub.charAt(i) - '0';
while (sub.charAt(i+1) - '0' >= 0 && sub.charAt(i+1) - '9' <= 0) {
i++;
subCount = subCount * 10 + sub.charAt(i) - '0';
}
int start = i+2;
int num = 1;
String subsub = "";
for (i = i+2; i < sub.length(); i++) {
if (sub.charAt(i) - '[' == 0) num++;
else if (sub.charAt(i) - ']' == 0) num--;
if (num == 0) {
subsub = sub.substring(start, i);
break;
}
}
trueStr = trueStr + decodeSub(subsub, subCount);
} else {
trueStr = trueStr + sub.substring(i, i+1);
}
}
String decodeRes = "";
for (int i = 0; i < count; i++) {
decodeRes = decodeRes + trueStr;
}
return decodeRes;
}
}
合集:https://github.com/Cloudox/LeetCode-Record