개발공부/코딩테스트 연습문제

[프로그래머스] Level.2 - 전화번호 목록 (JAVA)

ku-na 2022. 1. 21. 10:46

문제 설명과 제한사항

풀이

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++){
            String num1 = phone_book[i];
            String num2 = phone_book[i+1];
            if(num1.length() < num2.length() && num1.equals(num2.substring(0,num1.length()))){
                return false;                
            }
        }
        return answer;
    }
}

 

++

발상은 쉽게 됐다.

1. String[] (문자열) 배열 이기 때문에 정렬하면 사전순으로 정렬 됨. 

2. 정렬 후 다음 문자열과 비교하면 됨.

그렇게 코드를 짜다보니 다음 문자열이 이전 문자열보다 짧으면 에러가 뜨게 됨.

그래서 조건을 추가하다보니 조건이 너무 길어서 num1, num2 를 선언함.

 

다른 사람의 풀이를 보니 같은 방식으로 contains 로 푼 사람들이 있었는데..

contains는 접두사만 체크하는게 아니기 때문에 문제가 발생할 수 있었다.

 

또 다른 사람의 풀이는 startsWith로 푼 사람이 있었다..

좋은 발상인 것 같다. startsWith로 풀면 다음과 같다.

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

깔-끔.