본문 바로가기
코딩테스트 문제집/Programmers(Lv2)

[Programmers] Lv2: 전화번호 목록(42577)

by cogito30 2025. 2. 16.

문제

- 링크: https://school.programmers.co.kr/learn/courses/30/lessons/42577?language=java

 

풀이

(풀이1)

더보기
import java.util.*;

class Solution {
    public boolean solution(String[] phone_book) {
        boolean answer = true;
        
        Arrays.sort(phone_book);
        
        for (int i = 0; i < phone_book.length - 1; ++i) {
            if (phone_book[i + 1].startsWith(phone_book[i])) {
                answer = false;
            }
        }
        return answer;
    }
}

(풀이2)

더보기
import java.util.*;

class Solution {
    public boolean solution(String[] phone_book) {
        boolean answer = true;
        
        Arrays.sort(phone_book);
        
        for (int i = 0; i < phone_book.length - 1; ++i) {
            
            for (int j = 0; j < phone_book[i].length(); ++j) {
                if (phone_book[i].charAt(j) != phone_book[i + 1].charAt(j)) {
                    break;
                }
                if (j + 1 == phone_book[i].length()) {
                    answer = false;
                }
            }
        }
        return answer;
    }
}