Post

[BaekJoon] #1152 - 단어의 개수 [Java][C++]

[BaekJoon] #1152 - 단어의 개수 [Java][C++]

문제 링크


1. 아이디어

주어진 입력에서 단어의 개수를 구하는 간단한 문제다. 각 단어를 공백으로 구분해 토큰처럼 생각해서 해결했다.


2. 복잡도

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

($N$ = 입력 문자열의 길이)


3. 코드

풀이 [Java][C++]

1
2
3
4
5
6
7
8
9
10
import java.io.*;
import java.util.*;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        System.out.println(new StringTokenizer(br.readLine()).countTokens());
    }
}

StringTokenizer의 countTokens 메서드로 토큰의 개수를 바로 셀 수 있다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <bits/stdc++.h>
using namespace std;

int main() {
    ios::sync_with_stdio(0);
    cin.tie(0);

    string s;
    int cnt = 0;

    while (cin >> s) {
        cnt++;
    }

    cout << cnt;
}

This post is licensed under CC BY 4.0 by the author.