코딩테스트 풀이/JAVA
[프로그래머스/Lv.0] 외계어 사전
무지맘
2023. 2. 6. 21:50
1. Input
1) String[] spell
2) String[] dic
2. Output
1) spell에 있는 알파벳을 1번씩만 사용해 만들 수 있는 단어가 dic에 있다면 1, 없다면 2를 반환
3. Constraint
1) spell과 dic의 원소는 알파벳 소문자로만 이루어져있다.
2) 2 ≤ spell의 크기 ≤ 10
3) spell의 원소의 길이는 1
4) 1 ≤ dic의 크기 ≤ 10
5) 1 ≤ dic의 원소의 길이 ≤ 10
6) spell의 원소를 모두 사용해 단어를 만들어야 한다.
7) spell의 원소를 모두 사용해 만들 수 있는 단어는 dic에 1개뿐이다.
8) dic과 spell 모두 중복된 원소를 갖지 않는다.
4. Example
Input: spell=["p", "o", "s"], dic=["sod", "eocd", "qixm", "adio", "soo"] -> Output: 2
Input: spell=["z", "d", "x"], dic=["def", "dww", "dzx", "loveaw"] -> Output: 1
설명:
- dic의 단어 중 p, o, s로 만들 수 있는 단어가 없으므로 2를 반환한다.
- dic의 단어 중 z, d, x로 만들 수 있는 단어로 dzx가 있으므로 1을 반환한다.
5. Code
1) 첫 코드(2023/02/06)
import java.util.*;
ArrayList<String> dic_list = new ArrayList<String>(Arrays.asList(dic));
// 길이가 다른 dic의 단어 제거
for(int i=dic_list.size()-1 ; i>=0 ; i--){
if(dic_list.get(i).length()!=spell.length){
dic_list.remove(dic_list.get(i));
continue;
}
}
// spell의 알파벳을 모두 1번씩만 썼는지 확인
for(int i=dic_list.size()-1 ; i>=0 ; i--){
boolean isHere = true;
ArrayList<String> s = new ArrayList<String>(Arrays.asList(spell));
for(int j=0 ; j<dic_list.get(i).length() ; j++){
if(!s.contains(dic_list.get(i).substring(j,j+1))){
isHere = false; break;
} else
s.remove(dic_list.get(i).substring(j,j+1));
}
if(!isHere) dic_list.remove(dic_list.get(i));
}
return dic_list.size()==0 ? 2 : 1;