Decode String
题目链接:https://leetcode.com/problems...
stack的题,感觉还是分析下stack什么时候pop,什么时候push,思路会比较快。loop里面不加while循环的写法。
public class Solution {
public String decodeString(String s) {
/* stack to solve: store string & store number
* 2 variables: str, number
* 1. push: meet '['
* number to numberStack, str to stringStack
* reset number & str
* 2. pop: meet ']'
* pop number & str, append current str
* 3. meet number: update number
* 4. meet other characters: update str
* result: s
*/
Stack<String> stringStack = new Stack();
Stack<Integer> numberStack = new Stack();
String str = "";
int number = 0;
for(int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if(c == '[') {
// push
stringStack.push(str);
numberStack.push(number);
str = "";
number = 0;
}
else if(c == ']') {
String temp = str;
str = stringStack.pop();
for(int j = numberStack.pop(); j > 0; j--) {
str += temp;
}
}
else if(c >= '0' && c <= '9') number = number * 10 + (c-'0');
else str += c;
}
return str;
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。