难度 中等
括号运算的复杂版,主要是利用栈来先计算后面括号内的内容,再不断出栈到栈底。执行时间比较一般,想要继续优化可以改用StringBuilder,并在字母入栈时做些另外的处理。
执行用时 :2 ms, 在所有 Java 提交中击败了55.08%的用户
内存消耗 :38 MB, 在所有 Java 提交中击败了7.69%的用户
public String decodeString(String s) {
Stack<String> mStack = new Stack<String>();
for(int i = 0; i < s.length(); i++){
char ch = s.charAt(i);
if(ch == ']'){
String unitStr = "]";
while(!mStack.peek().equals("[")){
unitStr = mStack.pop() + unitStr;
}
unitStr = "[" + unitStr;
mStack.pop();
try{
while(Integer.parseInt(mStack.peek()) > -1){
unitStr = mStack.pop() + unitStr;
}
}catch(Exception ex){
}
unitStr = getUnitString(unitStr);
mStack.push(unitStr);
}else{
mStack.push(String.valueOf(ch));
}
}
String result = "";
while(mStack.size() > 0){
result = mStack.pop() + result;
}
return result;
}
String getUnitString(String x){
int n = 0;
int i = 0;
while(x.charAt(i) != '['){
n = n*10 + x.charAt(i) - 48;
i++;
}
i++;
String str = "";
while(x.charAt(i) != ']'){
str += String.valueOf(x.charAt(i));
i++;
}
String result = "";
while(n-- != 0){
result += str;
}
return result;
}