🚨 첫번째 실패한 풀이
✔️ 2중 for문
- 2중 for문으로 상호 비교
- startsWith로 같은지 비교
class Solution {
public boolean solution(String[] phone_book) {
for (int i = 0; i < phone_book.length; i++) {
int length = phone_book[i].length();
for (int j = 0; j < phone_book.length; j++) {
if (i != j && phone_book[j].length() >= length) {
if (phone_book[j].startsWith(phone_book[i])) {
return false;
}
}
}
}
return true;
}
}

💡 두번째 풀이
✔️ 1중 for문 사용
- 정렬하고 비교하면 뒷 번호가 앞 번호의 접두어인지 확인 안해도 됨
=> 2중 for문 x
import java.util.Arrays;
class Solution {
public boolean solution(String[] phone_book) {
Arrays.sort(phone_book);
for (int i = 0; i < phone_book.length - 1; i++) {
if (phone_book[i + 1].startsWith(phone_book[i])) {
return false;
}
}
return true;
}
}
💡 세번째 풀이
✔️ HashMap
- 전화번호를 모두 hashMap에 넣기
- 전화번호 길이만큼 순회
import java.util.HashMap;
class Solution {
public boolean solution(String[] phone_book) {
HashMap<String, Integer> hm = new HashMap<>();
for (int i = 0; i < phone_book.length; i++) {
hm.put(phone_book[i], i);
}
for (int i = 0; i < phone_book.length; i++) {
for (int j = 0; j < phone_book[i].length(); j++) {
if (hm.containsKey(phone_book[i].substring(0, j))) {
return false;
}
}
}
return true;
}
}