[LeetCode] 271 - Encode and Decode Strings
문제
- 링크: https://leetcode.com/problems/encode-and-decode-strings
- 난이도: Medium
- 태그: 배열, 문자열
- 결과:
Time: 22 ms (91.65%), Space: 25.80 MB (65.22%)
풀이
class Codec {
public:
// Encodes a list of strings to a single string.
string encode(vector<string>& strs) {
string str;
for(auto& s : strs)
{
str += s;
str.push_back(3);
}
return str;
}
// Decodes a single string to a list of strings.
vector<string> decode(string s) {
vector<string> v;
v.reserve(200);
string str_buf;
istringstream iss(s);
while (getline(iss, str_buf, (char)3))
{
v.push_back(str_buf);
}
return v;
}
};
입력으로 안들어 올만한 문자를 구분자로 써서 문자열을 합쳤다. 이게 큰 의미가 있는 문제인지 의문이 들었는데, 나와 비슷한 생각을 가진 사람이 남긴 댓글에 ‘문자열이 컴퓨터에서 어떻게 작동하는지 이해하는데 도움이 된다’는 답글을 봤다. 음, 딱히 동의가 되지는 않는다. 조금 더 제약이 있는게 나을 것 같다.
배운 점과 후기
getline을 통해 문자열을 delimeter 기준으로 split할 수 있다.
댓글남기기