|
| 1 | +# encode 메서드: |
| 2 | +# 시간 복잡도: O(N) |
| 3 | +# - 각 문자열을 한 번씩 순회하며 길이와 내용을 처리하므로, 모든 문자열 길이의 합에 비례. |
| 4 | +# 공간 복잡도: O(N) |
| 5 | +# - 인코딩된 결과 문자열을 저장하기 위해 추가 공간 사용. |
| 6 | + |
| 7 | +# decode 메서드: |
| 8 | +# 시간 복잡도: O(N) |
| 9 | +# - 인코딩된 문자열을 처음부터 끝까지 한 번 순회하며 파싱하므로, 입력 문자열 길이에 비례. |
| 10 | +# - s.find('#', i)는 인덱스 i부터 다음 #를 찾음. |
| 11 | +# - 여러 번의 find 호출이 있더라도 각 호출마다 전체 문자열을 다시 탐색하지 않고 이전 탐색 이후의 부분만 탐색하게 되어, 모든 find 호출을 합한 전체 탐색 거리는 인코딩된 문자열의 전체 길이 n에 해당함. 전체 시간은 O(n)에 수렴. |
| 12 | +# 공간 복잡도: O(N) |
| 13 | +# - 디코딩된 문자열 리스트를 구성하기 위해 추가 공간 사용. |
| 14 | + |
| 15 | + |
| 16 | +class Solution: |
| 17 | + """ |
| 18 | + @param strs: a list of strings |
| 19 | + @return: encodes a list of strings to a single string. |
| 20 | + """ |
| 21 | + def encode(self, strs): |
| 22 | + encoded_str = "" |
| 23 | + |
| 24 | + for s in strs: |
| 25 | + encoded_str += (str(len(s)) + "#" + s) |
| 26 | + |
| 27 | + return encoded_str |
| 28 | + |
| 29 | + """ |
| 30 | + @param s: A string |
| 31 | + @return: decodes a single string to a list of strings |
| 32 | + """ |
| 33 | + def decode(self, s): |
| 34 | + decoded_list = [] |
| 35 | + i = 0 |
| 36 | + while i < len(s): |
| 37 | + j = s.find("#", i) |
| 38 | + length = int(s[i:j]) |
| 39 | + i = j + 1 |
| 40 | + decoded_list.append(s[i:i + length]) |
| 41 | + i += length |
| 42 | + |
| 43 | + return decoded_list |
| 44 | + |
| 45 | + |
| 46 | +def main(): |
| 47 | + sol = Solution() |
| 48 | + |
| 49 | + # 테스트 예시 1 |
| 50 | + input_strings1 = ["lint", "code", "love", "you"] |
| 51 | + print("===== Example 1 =====") |
| 52 | + print("Original: ", input_strings1) |
| 53 | + encoded_str1 = sol.encode(input_strings1) |
| 54 | + print("Encoded: ", encoded_str1) |
| 55 | + decoded_list1 = sol.decode(encoded_str1) |
| 56 | + print("Decoded: ", decoded_list1) |
| 57 | + print() |
| 58 | + |
| 59 | + # 테스트 예시 2 |
| 60 | + input_strings2 = ["1234567890a", "we", "say", "#", "yes"] |
| 61 | + print("===== Example 2 =====") |
| 62 | + print("Original: ", input_strings2) |
| 63 | + encoded_str2 = sol.encode(input_strings2) |
| 64 | + print("Encoded: ", encoded_str2) |
| 65 | + decoded_list2 = sol.decode(encoded_str2) |
| 66 | + print("Decoded: ", decoded_list2) |
| 67 | + print() |
| 68 | + |
| 69 | + |
| 70 | +if __name__ == "__main__": |
| 71 | + main() |
0 commit comments