DeepRest

Decode String

Dec 19th, 2021 (edited)
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.98 KB | None | 0 0
  1. #APPROACH 1
  2. '''
  3. Using stack:
  4. Time: O(len of decoded string)
  5. Space: O(len of encoded string)
  6.  
  7. Intuition: To decode the string:
  8. 1. COPY ALPHABETS AS IT IS
  9. 2. ON DIGITS: FIND THE NUMERIC VALUE OF SEQUENCE OF CONSECUTIVE DIGITS (THEY WILL BE ENDED BY OPENING SQUARE BRACKET AND USED IN CASE 4 IN NEXT ITERATION)
  10. 3. ON ']', SUFFIX HAS TO BE REPEATED,
  11.   WHERE: STARTING POINT OF SUFFIX = POSITION OF CHARACTER IN RES FOLLOWING THE MATCHING OPENING BRACKET OF ']' (IN THE ORIGINAL STRING), AND
  12.          NUMBER OF REPETITION = NUMERIC VALUE OF DIGITS PRECEEDING THE MATCHING OPENING SQUARE BRACKET. - 1(REASON EXPLAINED IN CODE)
  13. 4. IN ORDER TO FIND THE MATCHING SQUARE OPENING BRACKET AND ITS RELATED INFO(GIVEN IN ABOVE POINT), USE STACK ( AS DONE IN PROBLEM OF WELL-FORMEDNESS OF PARENTHESIS).
  14.   THUS ON '[' PUSH TUPLE CONSISTING OF INTERGRAL VALUE FOUND AT CASE 2 IN PREVIOUS ITERATION(AS '[' IS ALWAYS PRECEEDED BY DIGITS) AND, CURRENT LENGTH OF RESULT (AS '[' IS ALWAYS FOLLOWED BY ALPHABETS AND THUS CURRENT LENGTH OF RESULT WOULD BE THE INDEX OF CHARACTER FOLLOWING '[' AD REQUIRED IN CASE 3)
  15. '''
  16. class Solution:
  17.     def decodeString(self, s: str) -> str:
  18.         stack = deque()
  19.         res = ""
  20.         rs = 0
  21.  
  22.         i, n, dig = 0, len(s), ""
  23.         while i < n:
  24.             if s[i].isalpha():
  25.                 res += s[i] #alphabets copied as it is and length incremented
  26.                 rs += 1
  27.            
  28.             elif s[i].isdigit():
  29.                 dig += s[i] #keep track of consecutive digits before '['(it is the no. of times following enclosed content has to be repeated)
  30.                
  31.             elif s[i] == '[':
  32.                 stack.append((int(dig)-1, rs)) #stack contains two info related to '[': 1. Numeric value of digits before it minus one(as the content to be repeated will be already written once by first if case), and the current length of result(as it is origin point for the repetition)
  33.                 dig = "" #the sequence of digits end at '[', thus reset
  34.  
  35.             else: #s[i] == ']'
  36.                 ele = stack.pop()
  37.                 cyc = (rs - ele[1]) #length of the suffix starting at ele[1] of res to be repeated ele[0] times
  38.                 for _ in range(cyc * ele[0]):
  39.                     res += res[-cyc]
  40.                     rs += 1
  41.             i += 1
  42.            
  43.         return res
  44.  
  45.  
  46. #APPROACH 2: Recursive implementation of the same (using dfs)
  47. '''
  48. class Solution:
  49.    idx = -1
  50.    def decodeString(self, s: str) -> str:
  51.        self.idx += 1
  52.        res, dig = "", ""
  53.        while self.idx < len(s):
  54.            if s[self.idx].isalpha():
  55.                res += s[self.idx]
  56.            
  57.            elif s[self.idx].isdigit():
  58.                dig += s[self.idx]
  59.            
  60.            elif s[self.idx] == '[':
  61.                res += (self.decodeString(s)) * int(dig)
  62.                dig = ""
  63.            
  64.            else:
  65.                return res
  66.            
  67.            self.idx += 1
  68.        
  69.        return res
  70. '''
Add Comment
Please, Sign In to add comment