Advertisement
Iam_Sandeep

394. Decode String

Jul 11th, 2022
814
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.96 KB | None | 0 0
  1. class Solution:
  2.     def decodeString(self, s: str) -> str:
  3.         st=[]
  4.         for i in s:
  5.             #if not '[' just add
  6.             if i!=']':
  7.                 st.append(i)
  8.             else:
  9.                 # Sinec we got ] we have to pop till we make a block enclosing [ and store it in subs
  10.                 subs=''
  11.                 while st[-1]!='[':
  12.                     subs=st.pop()+subs
  13.                 st.pop()
  14.                 #now check any number preceding this block. Note this number might have more than one digit. So check
  15.                 #till its preceding character is no more a digit
  16.                 #Then multiply this number with the block and add to stack again.
  17.                 num=''
  18.                 while st and st[-1].isdigit():
  19.                     num=st.pop()+num
  20.                 st.append(subs*int(num))
  21.         #Now currently stack holds all independent blocks and just return them by joining
  22.         return ''.join(st)
  23.        
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement