nathanwailes

LeetCode 271 - Encode and Decode Strings - 2023.03.27 solution

Mar 26th, 2023
156
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.23 KB | None | 0 0
  1. class Solution:
  2.     """
  3.    @param: strs: a list of strings
  4.    @return: encodes a list of strings to a single string.
  5.  
  6.    Thought process: If we just use a delimiter we always risk having that
  7.    delimiter show up in our input.
  8.  
  9.    So the safest way to do it is to read in numbers until we hit a known delimiter,
  10.    then convert those characters to a number, and read in that many characters
  11.    for the next string.
  12.    """
  13.     def encode(self, strs):
  14.         output = ''
  15.         for item in strs:
  16.             output += str(len(item)) + '#' + item
  17.         return output
  18.  
  19.     """
  20.    @param: str: A string
  21.    @return: dcodes a single string to a list of strings
  22.    """
  23.     def decode(self, str):
  24.         # write your code
  25.         i = j = 0
  26.         print(str)
  27.         output = []
  28.         while j < len(str):
  29.             if str[j] == '#':
  30.                 print(i, j)
  31.                 next_string_start_index = j + 1
  32.                 next_string_end_index = next_string_start_index + int(str[i:j]) - 1
  33.                 output.append(str[next_string_start_index:next_string_end_index + 1])
  34.                 i = next_string_end_index + 1
  35.                 j = i + 1
  36.                 continue
  37.             j += 1
  38.         return output
Advertisement
Add Comment
Please, Sign In to add comment