[Java] 백준 2607번: 비슷한 단어

U·2024년 10월 10일

백준

목록 보기
61/116

[문제 바로 가기] - 비슷한 단어

💡 접근 방식

문제의 조건에서는 결국 두 단어가 알파벳 한 개 이하 차이가 나야한다는 것이다.
그래서 단어 각각의 List를 만들어 contains로 첫번째 단어의 알파벳 존재 여부를 확인한다. 존재한다면 두 List에서 모두 해당 알파벳을 지운다.
이 과정이 끝난 후 두 List의 크기가 모두 1 이하이면 count++ 해준다.


풀이

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

/**
 * 백준 2607번 비슷한 단어
 * 1. 들어가 있는 문자는 모두 같은데 순서가 다를 경우
 * 2. 한 문자를 더할 경우
 * 3. 한 문자를 뺄 경우
 * 4. 한 문자를 다른 문자로 바꿀 경우
 * => 각 List에 알파벳 하나씩 넣어서 contains로 확인하고 겹치는 것은 지워서 마지막에 남은 개수 확인
 */

public class Main {
	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		int n = Integer.parseInt(br.readLine());
		
		int count = 0;
		
		String str = br.readLine();
		
		for (int i = 0; i < n - 1; i++) {
			String word = br.readLine();
			List<String> list = new ArrayList<>();
			List<String> newWord = new ArrayList<>();
			
			for (int j = 0; j < str.length(); j++) {
				list.add(str.split("")[j]);
			}
			
			for (int j = 0; j < word.length(); j++) {
				newWord.add(word.split("")[j]);
			}

			for (int j = 0; j < word.length(); j++) {
				if (list.contains(word.charAt(j) + "")) {
					list.remove(word.charAt(j) + "");
					newWord.remove(word.charAt(j) + "");
				}
			}
			
			if (list.size() <= 1 && newWord.size() <= 1) count++;
			
		}
		
		System.out.println(count);
	}
}
profile
백엔드 개발자 연습생

0개의 댓글