[프로그래머스]전화번호 목록

ByWindow·2020년 11월 11일
0
post-thumbnail

1. 문제

문제 설명

전화번호부에 적힌 전화번호 중, 한 번호가 다른 번호의 접두어인 경우가 있는지 확인하려 합니다.
전화번호가 다음과 같을 경우, 구조대 전화번호는 영석이의 전화번호의 접두사입니다.

구조대 : 119
박준영 : 97 674 223
지영석 : 11 9552 4421

어떤 번호가 다른 번호의 접두어인 경우가 있으면 false를 그렇지 않으면 true를 return한다.

제한사항

  • phone_book의 길이는 1 이상 1,000,000 이하입니다.
  • 각 전화번호의 길이는 1 이상 20 이하입니다.

입출력 예

phone_bookreturn
[119, 97674223, 1195524421]false
[123,456,789]true
[12,123,1235,567,88]false

2. 아이디어

2중 for문을 돌면서 밖의 for문에서 가리키는 값과 안의 for문이 가리키는 값을 비교한다
접두어인지를 판단하는 로직은 equals() 와 substring(0, 문자열길이) 로 구현했다.

3. 코드

public class phoneBookList {

    public static boolean solution(String[] input){
        boolean output = true;
        boolean breakpoint = false;
        for(int i = 0; i < input.length; i++){
            for(int j = 0; j < input.length; j++){
                if(i != j && input[i].length() <= input[j].length()){
                    if(input[i].equals(input[j].substring(0,input[i].length()))) {
                        output = false;
                        breakpoint = true;
                        break;
                    }
                }
            }
            if(breakpoint) break;
        }
        return output;
    }
    public static void main(String[] args) {
        String[] input = {"119", "97674223", "1195524421"};
        System.out.println(solution(input));
    }
}

다른 분의 코드도 첨부하겠다

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

접두어를 비교할 때 사용하기 좋은 startsWith()이라는 함수를 새롭게 알게 되었다!
String의 배열을 정렬하면 사전순으로 정렬되기 때문에 젤 첫 글자가 작은 것부터 정렬된다는 사실을 알게 되었따!!

4. end...

https://jamesdreaming.tistory.com/86
끝으로 startsWith 와 endWith에 대해 참고할만한 자료를 첨부하고 포스팅을 마치겠다😁

profile
step by step...my devlog

4개의 댓글

comment-user-thumbnail
2020년 11월 12일

말투가 약간 싸가지가,,,

1개의 답글