首页 > 代码库 > Leetcode: Decode String

Leetcode: Decode String

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".

自己的做法:这种括号问题肯定是用栈,最好是先在栈里存一个空元素,然后stack.peek().append()各种操作

一个栈存string, 一个栈存number, 维护一个指针numStart指向数字的开始

1. 遇到数字啥也不做

2. 遇到char: stack.peek().append(char), 然后更新numStart 

3. 遇到‘[’: stack.push(new StringBuffer()), numStack.push(number), 然后更新numStart

4. 遇到‘]‘:str=stack.pop(), 然后numStack pop得到重复次数,按此次数append str到stack.peek()

 

 1 public class Solution {
 2     public String decodeString(String s) {
 3         if (s==null || s.length()==0) return "";
 4         StringBuffer res = new StringBuffer();
 5         Stack<StringBuffer> resStack = new Stack<StringBuffer>();
 6         Stack<Integer> numStack = new Stack<Integer>();
 7         resStack.push(res);
 8         int numStart = 0;
 9         
10         for (int i=0; i<s.length(); i++) {
11             char c = s.charAt(i);
12             if (isChar(c)) {
13                 resStack.peek().append(c);
14                 numStart = i+1;
15             }
16             else if (c == ‘[‘) {
17                 int num = Integer.parseInt(s.substring(numStart, i));
18                 numStack.push(num);
19                 resStack.push(new StringBuffer());
20                 numStart = i+1;
21             }
22             else if (c == ‘]‘) {
23                 int num = numStack.pop();
24                 StringBuffer str = resStack.pop();
25                 for (int j=0; j<num; j++) {
26                     resStack.peek().append(str);
27                 }
28                 numStart = i+1;
29             }
30         }
31         return res.toString();
32     }
33     
34     public boolean isChar(char c) {
35         if (c>=‘a‘ && c<=‘z‘ || c>=‘A‘ && c<=‘Z‘) return true;
36         return false;
37     }
38 }

 

Leetcode: Decode String