Leetcode 394. Decode String
题目
s = "3[a]2[bc]", return "aaabcbc".
s = "3[a2[c]]", return "accaccacc".
s = "2[abc]3[cd]ef", return "abcabccdcdcdef".思路
解答
class Solution {
public String decodeString(String s) {
Stack<Integer> kstack = new Stack<Integer>(); // stores the multiplier
Stack<String> strstack = new Stack<String>(); // stores all intermediate str
String str = ""; // result string
int k = 0; // multipler before each number
for (char ch : s.toCharArray()) {
// Construct the multipler k
if (Character.isDigit(ch)) {
k = k * 10 + Character.getNumericValue(ch);
continue;
}
switch(ch) {
case '[': // end of multipler
kstack.push(k);
strstack.push(str);
k = 0;
str = "";
break;
case ']': // end of current str
int repeatedTimes = kstack.pop();
StringBuilder prev_res = new StringBuilder(strstack.pop());
for (int i = 0; i < repeatedTimes; i++) {
prev_res.append(str);
}
str = prev_res.toString();
break;
default: // normal char
str += ch;
break;
}
}
return str;
}
}Complexity Analysis
拓展
总结
Reference
Last updated