본문 바로가기
🖥️ 문제 풀이/리트코드(Leetcode)

[LeetCode 해석 및 풀이] 271. String Encode and Decode

by 뒬탕 2024. 5. 6.
반응형

LeetCode 문제 해석 및 풀이 방법

 

문제 271. String Encode and Decode(문자열을 인코드, 디코드하기 )

바로가기 무료버전 바로가기

문제 설명

영문

Design an algorithm to encode a list of strings to a single string. The encoded string is then decoded back to the original list of strings.

Please implement encode and decode

한글

리스트의 문자열을 하나의 문자열로 인코드하는 알고리즘을 작성하시오. 그런 다음 인코딩된 문자열은 원래 문자열 목록으로 다시 디코딩됩니다.

 

encode와 decode를 구현하십시오.

 

제한조건

  • 0 <= strs.length < 100
  • 0 <= strs[i].length < 200
  • strs[i] contains only UTF-8 characters.

 

입출력 예

입력 출력
["neet","code","love","you"] ["neet","code","love","you"]
["we","say",":","yes"] ["we","say",":","yes"]

 

 

해답 및 해설

파이썬 (Python)

class Solution:
    def encode(self, strs: List[str]) -> str:
        if not strs:
            return '다'
        return '가'.join(strs)
    def decode(self, s: str) -> List[str]:
        if s == '다':
            return []
        return s.split('가')

테스트 케이스에 한글은 없어서 가능한 풀이. 하지만 원칙상으로는 입력에 모든 UTF-8이 들어가므로 한글로도 쓰면 되지 않는다.

 

class Solution:
    
    def encode(self, strs: List[str]) -> str:
        res = ""
        for s in strs:
            res += str(len(s)) + "#" + s
        return res

    def decode(self, s: str) -> List[str]:
        res = []
        i = 0
        
        while i < len(s):
            j = i
            while s[j] != '#':
                j += 1
            length = int(s[i:j])
            i = j + 1
            j = i + length
            res.append(s[i:j])
            i = j
            
        return res

neetcode에서는 다음과 같이 '글자의 길이'+#+'글자 내용'으로 정리해서 문자열로 만드는 풀이를 적었다. 이러면 어떤 문자가 있어도, 문자에 숫자+# 문구가 포함되어 있어도 상관없다.

반응형

댓글