코딩테스트 공부

해시-전화번호 목록

구 승 2024. 8. 27. 16:48

 

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])){
                return false;
            }
        }
        return answer;
        
    }
}

1.Arrays.sort를 사용하여 phone_book의 순서를 정렬한다.

-정렬을 해야지 1번째 순서와 2번째 순서가 인접한 번호로 정렬되기 때문에 접두사를 찾기 수월하다.

2. 반복문을 통해 처음부터 마지막까지 돌린다.(i+1을 해야되기 때문에 length-1이 아닌 length를 쓰면 에러가 난다)

3. startsWith 메서드를 사용하여 i+1의 문자열과 i의 문자열을 비교한다.

-startsWith 메서드는 접두사를 확인하기위해 사용되는 메서드이다.

-아래는 예시

String str = "hello world";

// "hello"로 시작하는지 확인
boolean result1 = str.startsWith("hello"); // true

// "world"로 시작하는지 확인
boolean result2 = str.startsWith("world"); // false

-contains를 startsWith대신 써도 문제는 해결되지만 contains는 접수사가 아닌 str문자열에 있는 문자면 true를 출력하기에 문제 의도와는 조금 거리가 멀다.( contains는 문자열 안에 특정 문자열이 어디에 있든지 포함되어 있는지를 확인)

-아래는 예시

String str = "hello world";

// "hello"를 포함하는지 확인
boolean result1 = str.contains("hello"); // true

// "world"를 포함하는지 확인
boolean result2 = str.contains("world"); // true

// "ow"를 포함하는지 확인
boolean result3 = str.contains("ow"); // true

// "world!"를 포함하는지 확인
boolean result4 = str.contains("world!"); // false

 

4.if문을 통해 startsWith를 써서 포함되어있다면 원래는 true를 반환하지만 문제에서는 false를 반환하라고 했기 때문에 false를 return 해준다.