394. Decode String

Posted gopanama

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了394. Decode String相关的知识,希望对你有一定的参考价值。

 

用curString去记录前面的String的结果

 

 1 class Solution {
 2     public String decodeString(String s) {
 3         if(s.length() == 0) return "";
 4         char[] arr = s.toCharArray();
 5         Stack<String> stack = new Stack<>();
 6         int i = 0;
 7         String curString = "";
 8         while(i < s.length()){
 9             if(Character.isDigit(arr[i])){
10                 String num = "";
11                 while(Character.isDigit(arr[i])){
12                     num += arr[i];
13                     i++;
14                 }
15                 stack.push(num);
16             }
17             if(arr[i] == ‘[‘){
18                 stack.push(curString);
19                 curString = "";
20                 i++;
21                 continue;
22             }
23             if(arr[i] == ‘]‘){
24                 String prev = stack.pop();
25                 String num = stack.pop();
26                 int j = Integer.parseInt(num);
27                 String temp = curString;
28                 for(int k = 0; k < j-1; k++){
29                     curString += temp; 
30                 }
31                 curString = prev + curString;
32                 i++;
33             }else{
34                 curString += arr[i]; 
35                 i++;
36             }
37             
38         }
39         return curString;    
40     }
41 }

 

以上是关于394. Decode String的主要内容,如果未能解决你的问题,请参考以下文章

394. Decode String

Python 解LeetCode:394 Decode String

[LC] 394. Decode String

394. Decode String

Leetcode -- 394. Decode String

Leetcode 394: Decode String