271. Encode and Decode Strings
오늘은 릿코드 271번 문제 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.
Machine 1 (sender) has the function:
string encode(vector<string> strs) {
// ... your code
return encoded_string;
}
Machine 2 (receiver) has the function:
vector<string> decode(string s) {
//... your code
return strs;
}
So Machine 1 does:
string encoded_string = encode(strs);
and Machine 2 does:
vector<string> strs2 = decode(encoded_string);
strs2 in Machine 2 should be the same as strs in Machine 1.
Implement the encode and decode methods.
Note:
- The string may contain any possible characters out of 256 valid ascii characters. Your algorithm should be generalized enough to work on any possible characters.
- Do not use class member/global/static variables to store states. Your encode and decode algorithms should be stateless.
- Do not rely on any library method such as eval or serialize methods. You should implement your own encode/decode algorithm.
문제의 내용은 ["Hello", "World"] 와 같은 문자열 배열이 들어올 경우 "HelloWorld" 와 같이 스트링 인코딩을, 또 스트링에서 다시 ["Hello", "World"] 문자열 배열로 디코딩을 해주는 코드를 작성하는 것입니다.
해당문제는 문자와 문자를 나누는 Delimeter 값으로 ASCII 코드가 아닌 값을 넣음으로써 문제를 쉽게 접근 해 보겠습니다.
문제풀이
/**
* Non-ASCII Delimiter
* @param {string[]} strs
* @return {string}
*/
const encode = (strs, nonASCIICode = String.fromCharCode(257)) => {
return strs.join(nonASCIICode);/* Time O(N) | Ignore Auxillary Space O(N) */
};
/**
* Non-ASCII Delimiter
* @param {string[]} strs
* @return {string}
*/
const decode = (strs, nonASCIICode = String.fromCharCode(257)) => {
return strs.split(nonASCIICode);/* Time O(N) | Ignore Auxillary Space O(N) */
};
스트링 빌트인 함수인 join 을 이용해 nonASCIICode 를 임의로 설정해서
fromCharCode 또한 자바스크립트의 스트링 빌트인 함수로 인자로 받은 값을 그대로 문자로 출력해 줍니다.
이 값을 Delimeter로 가지게 되면 문자열 내에 또는 문자열 배열 내에 구분자로 'ā' 값을 넣게 되어 인코딩 / 디코딩을 합니다.
예를들면, ["Hello", "World"] 와 같은 문자열 배열이 들어올 경우 "HelloāWorld" 와 같이 스트링 인코딩을, 또 "HelloāWorld" 스트링에서 다시 ["Hello", "World"] 문자열 배열로 디코딩을 해주는 코드를 작성하는 것입니다.
이 문제 해결 접근 방법은 문자열 또는 문자열 배열 내에 아스키 코드 값만 가지고 있다 라고 하는 전제를 두고 있습니다.
이상 릿코드 271번 문제 Encode and Decode Strings를 풀어보았습니다.
※ 앞으로 모든 문제를 JavaScript 로 올릴 예정입니다.
다른 문제 풀이도 깃헙에서 확인 할 수 있습니다.
'Software Development > Leetcode' 카테고리의 다른 글
Leetcode 125. Valid Palindrome (0) | 2023.01.19 |
---|---|
Leetcode 128. Longest Consecutive Sequence (0) | 2023.01.19 |
Leetcode 238. Product of Array Except Self (0) | 2023.01.19 |
Leetcode 347. Top K Frequent Elements (0) | 2023.01.15 |
Leetcode 49. Group Anagrams (0) | 2023.01.14 |
댓글