import java.util.ArrayList;
import java.util.List;
class Solution {
public int solution(String[] spell, String[] dic) {
List<String> list = new ArrayList<>();
for(int i=0; i<dic.length; i++) {
list.add(dic[i]);
}
List<String> temp = new ArrayList<>();
for(int i=0; i<spell.length; i++) {
for(int j=0; j<list.size(); j++) {
if(list.get(j).contains(spell[i])) {
temp.add(list.get(j));
}
}
list.clear();
for(int k=0; k<temp.size(); k++) {
list.add(temp.get(k));
}
temp.clear();
}
int answer = 2;
if(list.size() >=1) answer =1;
return answer;
}
}
다른 풀이를 보니, 코드가 더 깔끔하기도하고 시간 복잡도나 공간복잡도나 조금이라도 덜 사용하기때문에 다른 코드를 공부한다.
class Solution {
public int solution(String[] spell, String[] dic) {
int answer = 2;
for(String dicS : dic) {
boolean isRight = true;
for(String spellS : spell) {
if(dicS.indexOf(spellS) == -1) {
isRight = false;
break;
}
}
if(isRight) {
answer = 1;
break;
}
}
return answer;
}
향상된 for문을 사용해 코드를 더욱 깔끔하게 작성할 수 있다.
기준(바깥 for문)을 사전으로해서 하나씩 spell의 값이 포함되어있는지 체크하며, 없는경우에는 바로 반복문을 끝내도되게 할 수 있다.
indexOf()를 이용해 문자열이 있는지 판단할 수 있다.
boolean값을 이용해서 반복문을 빠져나오게 할 수 있고, 마지막에 출력해야 할 변수값도 업데이트할 수 있다.