Hash 사용
package com.company;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class Solution {
static public void main(String[] args) {
Solution testSolution = new Solution();
String[] quizArr1 = {"119", "97674223", "1195524421"};
String[] quizArr2 = {"123", "456", "789"};
String[] quizArr3 = {"12", "123", "1235", "567", "88"};
String[] quizArr4 = {"115524421", "119", "1197674223", "1234", "1235", "456", "567", "789", "88"};
System.out.println(testSolution.solution(quizArr1));
System.out.println(testSolution.solution(quizArr2));
System.out.println(testSolution.solution(quizArr3));
System.out.println(testSolution.solution(quizArr4));
}
public boolean solution(String[] phone_book) {
Set<String> set = new HashSet<String>(Arrays.asList(phone_book));
for (String phone : phone_book) {
for (int i = 1; i < phone.length(); i++) {
if(set.contains(phone.substring(0, i))) return false;
}
}
return true;
}
}
아이디어 구현 - 사전순 정렬 후 좌우 옆을 비교
package com.company;
import java.util.Arrays;
public class Solution {
static public void main(String[] args) {
Solution testSolution = new Solution();
String[] quizArr1 = {"119", "97674223", "1195524421"};
String[] quizArr2 = {"123", "456", "789"};
String[] quizArr3 = {"12", "123", "1235", "567", "88"};
String[] quizArr4 = {"115524421", "119", "1197674223", "1234", "1235", "456", "567", "789", "88"};
System.out.println(testSolution.solution(quizArr1));
System.out.println(testSolution.solution(quizArr2));
System.out.println(testSolution.solution(quizArr3));
System.out.println(testSolution.solution(quizArr4));
}
public boolean solution(String[] phone_book) {
boolean answer = true;
Arrays.sort(phone_book);
for (int i = 0; i < phone_book.length - 1; i++) {
if(i + 1 < phone_book.length && phone_book[i + 1].startsWith(phone_book[i]))
return false;
}
return answer;
}
}