码迷,mamicode.com
首页 > 其他好文 > 详细

394. Decode String

时间:2018-12-09 10:43:57      阅读:151      评论:0      收藏:0      [点我收藏+]

标签:color   cte   []   记录   dig   solution   push   ret   array   

 

用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

标签:color   cte   []   记录   dig   solution   push   ret   array   

原文地址:https://www.cnblogs.com/goPanama/p/10090174.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!