[LeetCode] String Encode and Decode

Yunju·2024년 10월 6일
0

String Encode and Decode

문제

내 답안

class Solution:

    def encode(self, strs: List[str]) -> str:
        res = ""
        if strs:
            res += strs[0]

        for s in strs[1:]: 
            res += "#" + s
        return res
        
    def decode(self, s: str) -> List[str]:
        res = []
        res = s.split('#')  # '#'을 기준으로 문자열을 나눔
        return res

-->Run으로 돌아가긴하는데, wrong answer 뜸

LeetCode Answers

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] != '#': # s[j]가 '#'이 아닐때까지 반복
                j+= 1
            length = int(s[i:j]) #첫번째 루프에서 length는 s[0:1] == 첫번째로 쓴 str(len(s)) 이 값..
            i = j + 1
            j = i + length
            res.append(s[i:j]) #이 때 추가됨.
            i=j

        return res
  • 그런데 의문이 듦. 만약에 'py#thon' 이런 글자도 구분을 할까? --> 결론: 구분함.
  • why? while s[j] != '#'는 leng(s) 다음 '#'을 찾기 위한것임. --> 그래서 항상 숫자 자리수 만큼만 while문 돎.
    또 의문이 듦. 그럼 #을 안넣고, 그냥 숫자만 넣어서 숫자만 가져오면 되지 않을까? --> 그럼 12, 20 이런 자리수를 가진 단어를 구분하지 못함.

0개의 댓글