import java.util.*;
class Solution {
public int solution(String[] spell, String[] dic) {
int answer = 2;
List<String> spell_list = new ArrayList<>();
for(int i = 0; i < spell.length; i++){
spell_list.add(spell[i]);
}
for(int i = 0; i < dic.length; i++){
List<String> list = new ArrayList<>();
for(int j = 0; j< dic[i].length(); j++){
list.add(String.valueOf(dic[i].charAt(j)));
}
if(list.containsAll(spell_list)){
return 1;
}
list.removeAll(list);
}
return answer;
}
}
내가 작성한 코드는 두개 다 리스트화 시켜서 각 리스트마다 조건에 부합한지 확인해주는 코드이다.
근데 이것보다 당연히 더 효율적인 코드가 있을 것 같아서 고민해보고 찾아봤다.
public static int solution(String[] spell, String[] dic) {
Set<String> spellSet = new HashSet<>(Arrays.asList(spell));
for (String word : dic) {
Set<String> wordSet = new HashSet<>(Arrays.asList(word.split("")));
if (wordSet.containsAll(spellSet)) {
return 1;
}
}
return 2;
}
이렇게 Set을 활용해서 짜면 중복된 원소도 제거하고
Set의 containsAll 메서드를 사용해서 조건 체크를 쉽게 할 수 있다.
그리고
for-each 와 split 을 사용해서 더 간결한 코드를 작성할 수 있었다.