1. 程式人生 > >394. Decode String

394. Decode String

push digi char color else [] git arr ont

用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