Advertisement
thewitchking

Untitled

Dec 14th, 2023
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.12 KB | None | 0 0
  1. class Solution {
  2.     public String decodeString(String s) {
  3.        
  4.         Stack<Integer> countStack = new Stack<>();
  5.         Stack<String> valueStack = new Stack<>();
  6.         StringBuilder sb = new StringBuilder();
  7.        
  8.         int idx = 0;
  9.         String res = "";
  10.         while(idx<s.length()){
  11.             if(Character.isDigit(s.charAt(idx))){
  12.                 int cnt = 0;
  13.                 while(idx<s.length() && Character.isDigit(s.charAt(idx))){
  14.                     cnt = cnt*10+(s.charAt(idx)-'0');
  15.                     idx++;
  16.                 }
  17.                 countStack.add(cnt);
  18.             }else if(s.charAt(idx)=='['){
  19.                 valueStack.add(res);
  20.                 res="";
  21.                 idx++;
  22.             }else if(s.charAt(idx)==']'){
  23.                 StringBuilder tmp = new StringBuilder(valueStack.pop());
  24.                 int repeat = countStack.pop();
  25.                 for(int i=0;i<repeat;++i)
  26.                     tmp.append(res);
  27.                 res = tmp.toString();
  28.                 idx++;
  29.             }else
  30.                 res+=s.charAt(idx++);
  31.         }
  32.         return res;
  33.     }
  34. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement