본문 바로가기
프로그래머스/코딩연습1

[프로그래머스] (틀림)단어 변환 (java)(43163)

by 유줘니 2019. 6. 10.

원본 문제 : https://programmers.co.kr/learn/courses/30/lessons/43163?language=java

 

 

 

테스트 케이스 3번에서 문제 발생, 3번 케이스의 return 값은 9가 정답.

 

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

class Solution {
    public int solution(String begin, String target, String[] words) {
        int answer = words.length;
        
        Set<String> set = new HashSet<String>();
        for(String s : words)
        	set.add(s);
        if(!set.contains(target)) return 0;
        
        answer = Math.min(answer, dfs(words, begin, target, 0));
        
        if(answer>words.length) return 0;
        return answer;
    }
    
    public static int dfs(String[] words, String begin, String target, int idx) {
		
		char[] beArr = begin.toCharArray();
		Set<Character> beSet = new HashSet<Character>();
		for(char ch : beArr)
			beSet.add(ch);
		int target_cnt = 0;
		for(int i = 0 ; i < words[0].length() ; i++) {
			if(beSet.contains(target.charAt(i)))
				target_cnt++;
			if(target_cnt==2) return 1;
		}
		
		if(idx>=words.length)
			return words.length;
		
		int cnt = 0;
		while(cnt < 2) {
			char chArr[] = words[idx].toCharArray();
			Set<Character> set = new HashSet<Character>();
			for(char ch : chArr)
				set.add(ch);
			for(int i = 0; i < words[0].length() ; i++)
				if(set.contains(begin.charAt(i)))
					cnt++;
			if(idx==words.length) break;
			if(cnt<2) {
				idx++;
			}
		}
		
		return 1+dfs(words,words[idx],target,idx+1);
	}
}

댓글