자료구조와 알고리듬 With Java/[Study] BAEKJOON 프로그래머스 CodeUp LeetCode

Baek joon 5052 전화 번호

계란💕 2022. 6. 15. 19:28

  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();
    } 
}

 

 

 

  출처: https://www.acmicpc.net/problem/5052