Ex) 전화 번호 목록
- sort와 startsWith를 이용한다.
- phone_book[i].startsWith(phone_book[i-1]) : phone_book[i-1]가 phone_book[i]의 접두사인지 확인한다.
- Arrays.sort(배열명): 배열을 오름차순으로 정렬한다.
Sol)
import java.util.*;
class Solution {
public boolean solution(String[] phone_book) {
Arrays.sort(phone_book); // sort로 정렬하면 119와 1195524421이 옆자리에 정렬된다.
for(int i = 1; i < phone_book.length; ++i){ //따라서, 바로 옆자리에 있는 수가 접두사인지 확인하면 된다.
if(phone_book[i].startsWith(phone_book[i-1])) return false;
}
return true;
}
}
MySol) - 시간 초과, 오류라고 나온다.
<hide/>
import java.util.Scanner;
public class Main {
// 전화번호
public static String solution(String[] numbers){
for(int i = 1; i < numbers.length; ++i){
for(int j = 0;j < i; ++j){
if(numbers[i].startsWith(numbers[j])){
return "NO";
}
}
}
return "YES";
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int caseCnt = scan.nextInt(); // 2개 경우 , 1보다 크다
for (int i = 0; i < caseCnt; ++i) { // 두 개 케이스
int numberCnt = scan.nextInt(); // 2개의 번호
String[] numbers = new String[numberCnt];
for (int j = 0; j < numberCnt; ++j) {
numbers[j] = scan.next();
}
System.out.println(solution(numbers));
}
scan.close();
}
}
'자료구조와 알고리듬 With Java > [Study] BAEKJOON 프로그래머스 CodeUp LeetCode' 카테고리의 다른 글
2022-06-29 [4회차] 알고리즘 스터디 (0) | 2022.06.29 |
---|---|
2022-06-22 [3회차] 알고리즘 스터디 (0) | 2022.06.22 |
Baekjoon 9375번 패션왕 신혜빈 (0) | 2022.06.11 |
Backjoon 7576 BFS 토마토 (0) | 2022.05.03 |
BFS 미로 찾기 (small) (0) | 2022.05.02 |