Post

[Programmers] #181868 - 공백으로 구분하기 2 [Java][C++][Python]

[Programmers] #181868 - 공백으로 구분하기 2 [Java][C++][Python]

문제 링크


1. 아이디어

단어가 공백 한 개 이상으로 구분되어 있는 문자열 my_string에 대해 각 단어를 순서대로 담은 문자열 배열을 반환하는 문제로 공백들을 기준으로 파싱만 해서 담으면 된다.


2. 복잡도

접근시간공간
풀이$O(N)$$O(N)$

($N$ = my_string의 길이)


3. 코드

풀이 [Java][C++][Python]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import java.util.*;

class Solution {
    public String[] solution(String my_string) {
        StringTokenizer st = new StringTokenizer(my_string);

        String[] arr = new String[st.countTokens()];
        for (int i = 0; i < arr.length; i++) {
            arr[i] = st.nextToken();
        }

        return arr;
    }
}

StringTokenizer를 활용해 공백들로 구분되는 각 단어만 토큰으로 새롭게 배열에 담았다.

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.