Blind 75/Array

Blind 75 | Encode and Decode Strings (Array 8 / 8)

penny! 2023. 6. 8. 13:06

https://leetcode.com/problems/encode-and-decode-strings

 

Encode and Decode Strings - LeetCode

Can you solve this real interview question? Encode and Decode Strings - Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

Encode and Decode Strings - 문자열의 인코딩과 디코딩

 

Design an algorithm to encode a list of strings to a string. The encoded string is then sent over the network and is decoded back to the original list of strings.

 

문자열이 담긴 배열을 인코딩하는 알고리즘을 디자인하라. 인코딩된 문자열은 네트워크로 전송되며 다시 원래의 문자열이 담긴 배열로 디코딩 된다.

 

 

간단하게 설명하자면

 

["a", "b", "c"]라는 배열이 주어진 후 인코딩하는 알고리즘으로 단 하나의 문자열로 만들고 

 

그걸 디코딩하는 알고리즘을 짜면 된다.

 

 

개요

 

문자열의 배열을 단 하나의 문자열로 만드는 알고리즘을 짤때는

 

문자열들의 사이에 현재 읽고 있는 문자열의 길이와 이를 구분할 문자를 넣어주면 디코딩할때

 

이를 이용하여 다시 문자열의 배열로 만들 수 있다.

 

 

 

풀이 방법

 

인코딩시에 ["Hello, "World"]가 있다면

 

Hello의 길이인 5를 문자열에 넣으면 "5"가 된다

 

그리고 여기서 임의의 특수문자를 넣는다. #를 선택해서 현재 문자열은 "5#". 어떤 문자여도 상관 없다.

 

이제 Hello를 넣어 "5#Hello", 이를 World까지 반복하면 "5#Hello5#World"가 된다.

 

 

디코딩시에 "5#Hello5#World"를 받게 되는데

 

문자열의 인덱스 0 부터 시작하여 #를 찾을때까지 읽는다.

 

#를 찾았다면 #전의 문자열을 숫자로 변환하면 단어의 길이가 된다.

 

그리고 그 길이를 이용하여 Hello를 배열에 넣는다. 그 과정을 문자열의 끝까지 반복한다.

 

 

 

 

풀이

 

 

 

이 문제가 요구하는 알고리즘 자체는 매우 간단하지만

 

항상 그렇듯이 이런 방법을 전에 본적이 없다면 떠올리기 힘들다.