※. 정렬로 풀 때 substring 대신 startsWith 사용해도 된다.
정렬
import java.util.Arrays;
class Solution {
public boolean solution(String[] phone_book) {
boolean answer = true;
Arrays.sort(phone_book);
for(int i = 1; i < phone_book.length; i++) {
if(phone_book[i].length() >= phone_book[i-1].length()) {
String temp = phone_book[i].substring(0,phone_book[i-1].length());
if(temp.equals(phone_book[i-1])) {
answer = false;
break;
}
}
}
return answer;
}
}
해시
import java.util.HashSet;
class Solution {
public boolean solution(String[] phone_book) {
boolean answer = true;
HashSet<String> hashset = new HashSet<>();
for(int i = 0; i < phone_book.length; i++) {
hashset.add(phone_book[i]);
}
for(int i = 0; i < phone_book.length; i++) {
for(int j = 1; j < phone_book[i].length(); j++) {
if(hashset.contains(phone_book[i].substring(0,j))) {
answer = false;
}
}
}
return answer;
}
}
'프로그래머스' 카테고리의 다른 글
[프로그래머스 Level 3] 기지국 설치 [Java] (0) | 2022.11.01 |
---|---|
[프로그래머스 Level 2] k진수에서 소수 개수 구하기 [Java] (0) | 2022.10.08 |
[프로그래머스 Level 2] 뉴스 클러스터링 [Java] (0) | 2022.10.01 |
[프로그래머스 Level 2] 위장 [Java] (0) | 2022.09.30 |
[프로그래머스 Level 2] 튜플 [Java] (2) | 2022.09.30 |