문제 설명

문자열 s가 있습니다. 이 문자열에는 여러 개의 단어가 공백으로 구분되어 적혀 있습니다.

이 문자열에서 중복된 단어를 제외한 단어의 수를 출력하는 프로그램을 구현하세요.


입력 형식

· s : 단어가 공백으로 구분된 문자열


출력 형식

· 중복을 제외한 단어의 수를 정수로 반환


제약 사항

· 1 <= s.length <= 1000

· s[i]는 영어 대소문자 또는 공백 문자이다.


입출력 예시

· 입력

  · s = "Hello world Nice world"

· 출력 : 3

· 설명 : 중복되는 world를 하나 제거하면, 단어의 수는 Hello, world, Nice로 총 3개다.


작성 코드

import java.util.HashSet;
import java.util.Set;

class Solution214 {
    public int solution(String s) {
        String[] words = s.split(" "); // 공백으로 문자열을 나눠 배열로 저장

        // 중복을 허용하지 않는 Set 컬렉션 생성
        Set<String> uniqueWords = new HashSet<>();
        // Set은 데이터를 중복 없이 저장하며, 'HashSet'은 데이터를 해싱 기반으로 저장하기 때문에
        // 검색 속도가 빠르다는 장점이 있다.

        for (String word : words) { // 배열의 모든 단어에 대해 반복
            uniqueWords.add(word); // Set에 단어 추가 (중복된 단어는 자동으로 제거됨)
        }
        return uniqueWords.size(); // Set의 크기 반환(중복 제외한 단어의 수)
    }

    public static void main(String[] args) {
        Solution214 st = new Solution214();
        String s = "Hello world Nice world";
        System.out.println(st.solution(s));
    }
}

 

정답 코드

import java.util.Arrays;
import java.util.stream.Collectors;

class Solution {
    public int solution(String s) {
        return Arrays.stream(s.split(" "))
                .collect(Collectors.toSet())
                .size();
    }

    public static void main(String[] args) {
        Solution st = new Solution();
        String s = "Hello world Nice world";
        System.out.println(st.solution(s));
    }
}