subject
Given an encoded string, return the decoded string.
The encoding rule is k[encoded_string], which means that the encoded_string within square brackets repeats exactly k times. Note that K is guaranteed to be a positive integer.
You can assume that the input string is always valid; there is no extra space in the input string, and the square brackets are always formatted.
In addition, you can assume that the original data does not contain numbers, and that all numbers represent only the number of repetitions k, such as no input like 3a or 2 [4].
Examples:
S = 3 [a] 2 [bc], returning "aaabcbc".
S = 3 [a2 [c], returns "accaccacc acc".
S = 2 [abc] 3 [cd] ef, return "abcabccdcdef".
Source: LeetCode
Links: https://leetcode-cn.com/problems/decode-string
Problem Solution
- Use stack.
- Note that the number may not be a single process.
- The code may be a bit verbose. You can pop up before you judge, not peek first. StringBuilder's operations need a second look.
Code
class Solution { public String decodeString(String s) { if(s==null){ return null; } Stack<Character> stack=new Stack<>(); for(int i=0;i<s.length();++i){ if(s.charAt(i)!=']'){ stack.push(s.charAt(i)); } else{ StringBuilder tempS=new StringBuilder(""); while(stack.peek()!='['){ tempS.append(stack.pop()); } String tempStr=tempS.reverse().toString(); stack.pop(); int num=0; int pos=1;// while(!stack.isEmpty()&&stack.peek()>='0'&&stack.peek()<='9'){// num+=(stack.pop()-'0')*pos;// pos*=10; } while(num--!=0){ for(int j=0;j<tempStr.length();++j){ stack.push(tempStr.charAt(j)); } } } } StringBuilder decodedStr=new StringBuilder(""); while(!stack.isEmpty()){ decodedStr.append(stack.pop()); } return decodedStr.reverse().toString(); } }