ALGORITHM

[JAVA] 백준 16499번- 동일한 단어 그룹화하기

연듀 2022. 7. 6. 13:12

https://www.acmicpc.net/problem/16499

 

16499번: 동일한 단어 그룹화하기

첫째 줄에 단어의 개수 N이 주어진다. (2 ≤ N ≤ 100) 둘째 줄부터 N개의 줄에 단어가 한 줄에 하나씩 주어진다. 단어는 알파벳 소문자로만 이루어져 있고, 길이는 10을 넘지 않는다.

www.acmicpc.net

 

import java.util.*;
public class Main{
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n=sc.nextInt();
        HashSet<String> hs = new HashSet<>();

        for(int i=0; i<n; i++){
            String str= sc.next();
            char[] word = str.toCharArray();
            Arrays.sort(word);
            hs.add(Arrays.toString(word));
        }
        System.out.println(hs.size());
    }
}

 

입력받은 문자열을 char형 배열에 담아 정렬해주고, 다시 문자열로 변환해 hashSet에 넣어준다.

hashSet은 중복 저장을 하지 않으므로 hashSet의 크기가 정답이 된다.