https://www.acmicpc.net/problem/2607
2607번: 비슷한 단어
첫째 줄에는 단어의 개수가 주어지고 둘째 줄부터는 한 줄에 하나씩 단어가 주어진다. 모든 단어는 영문 알파벳 대문자로 이루어져 있다. 단어의 개수는 100개 이하이며, 각 단어의 길이는 10 이
www.acmicpc.net
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
public class Main{
    public static HashMap<Character, Integer> map1, map2;
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int n= Integer.parseInt(br.readLine());
        String word = br.readLine();
        int answer=0;
        map1 = new HashMap<>();
        map2 = new HashMap<>();
       init(map1);
        for(int i=0; i<word.length(); i++){
            char ch = word.charAt(i);
            map1.replace(ch, map1.get(ch) + 1);
        }
        for(int i=0; i<n-1; i++){
            init(map2);
            String word2 = br.readLine();
            for(int j=0; j<word2.length(); j++){
                char ch = word2.charAt(j);
                map2.replace(ch, map2.get(ch) + 1);
            }
            if(isSimilar(map2)) answer++;
        }
        System.out.println(answer);
    }
    private static void init(HashMap<Character, Integer> hm){
        for(char ch='A';ch<='Z';ch++) hm.put(ch, 0);
    }
    public static boolean isSimilar(HashMap<Character, Integer> map2){
        // 문자열 알파벳 개수 차이가 2이하
        // 문자열의 길이 차이가 1 이하
        int a, b, diff=0, word1len =0, word2len=0;
        for(char ch='A'; ch<='Z'; ch++){
             word1len+= (a = map1.get(ch));
             word2len+= (b = map2.get(ch));
             diff+=Math.abs(a-b);
        }
        return diff<=2 && Math.abs(word1len-word2len) <=1;
    }
}
반응형
    
    
    
  'ALGORITHM' 카테고리의 다른 글
| [JAVA] 백준 10828번- 스택 (0) | 2022.10.04 | 
|---|---|
| [JAVA] 백준 1388번- 바닥 장식 (0) | 2022.10.03 | 
| [JAVA] 알고리즘 : DFS- 피자 배달 거리 (0) | 2022.09.30 | 
| [JAVA] 알고리즘 : DFS, BFS- 섬나라 아일랜드 (0) | 2022.09.30 | 
| [JAVA] 알고리즘 : DFS- 미로 탐색 (0) | 2022.09.29 |