[Programmers] #181869 - 공백으로 구분하기 1 [Java][C++][Python]
[Programmers] #181869 - 공백으로 구분하기 1 [Java][C++][Python]
1. 아이디어
단어가 공백 한 개로 구분되어 있는 문자열 my_string에 대해 각 단어를 순서대로 담은 문자열 배열을 반환하는 문제로 공백을 기준으로 파싱만 해서 담으면 된다.
2. 복잡도
| 접근 | 시간 | 공간 |
|---|---|---|
| 풀이 | $O(N)$ | $O(N)$ |
($N$ = my_string의 길이)
3. 코드
풀이 [Java][C++][Python]
1
2
3
4
5
class Solution {
public String[] solution(String my_string) {
return my_string.split(" ");
}
}
split(" ")을 활용해서 공백 한 개를 기준으로 토큰화한 배열을 바로 반환했다. 공백은 잘리면서 소비돼서 토큰에 포함되지 않는다.
1
2
3
4
5
6
7
8
9
10
11
#include <bits/stdc++.h>
using namespace std;
vector<string> solution(string my_string) {
stringstream ss(my_string);
vector<string> tokens;
string token;
while (ss >> token) tokens.push_back(token);
return tokens;
}
std::stringstream을 활용해 공백들을 기준으로 토큰을 분리해서 벡터에 담았다.
1
2
def solution(my_string):
return my_string.split()
split을 활용해서 공백들을 기준으로 토큰화한 리스트를 바로 반환했다. 공백들은 잘리면서 소비돼서 토큰에 포함되지 않는다.
This post is licensed under CC BY 4.0 by the author.