공부하는 블로그

Baekjoon | Q.5052 - 전화번호 목록 본문

알고리즘 공부

Baekjoon | Q.5052 - 전화번호 목록

치킨닮은닭 2020. 5. 16. 00:34
 

5052번: 전화번호 목록

문제 전화번호 목록이 주어진다. 이때, 이 목록이 일관성이 있는지 없는지를 구하는 프로그램을 작성하시오. 전화번호 목록이 일관성을 유지하려면, 한 번호가 다른 번호의 접두어인 경우가 없�

www.acmicpc.net

 전화번호 목록 중 한 번호가 다른 번호의 접두어가 되는지 판단하는 문제이다. 

 

import java.util.Arrays;
import java.util.Scanner;

class Main {
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    int tc = sc.nextInt();

    for (int i = 0; i < tc; i++) {
      int n = sc.nextInt();
      String[] tel = new String[n];
      String result = "YES";

      for (int j = 0; j < n; j++) {
        tel[j] = sc.next();
      }

      Arrays.sort(tel);

      for (int j = 0; j < n - 1; j++) {
        if(tel[j+1].startsWith(tel[j])) {
          result = "NO";
          break;
        }
      }
      
      System.out.println(result);
    }

  }
}

 

 전화번호 목록을 일일히 비교하는 방법은 비효율적이다. 접두어만 비교하면 되므로 받은 전화번호 목록 배열을 오름차순으로 정렬 후 arr[i+1]가 arr[i]로 시작하는지 'startsWith()'로 확인해주었다. 정렬은 자바에서 기본으로 제공하는 배열 정렬 메소드 'Arrays.sort()'를 사용했다.

 

'알고리즘 공부' 카테고리의 다른 글

Algorithm | DFS & BFS  (0) 2020.05.20
Algorithm | 자료구조 : Graph  (0) 2020.05.18
Algorithm | 자료구조 : Hash Table  (0) 2020.05.15
Algorithm | 자료구조 : Queue & Deque  (0) 2020.02.24
Algorithm | 자료구조 : Stack  (0) 2020.02.11
Comments