본문 바로가기

프로그래머스

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

 

 

 


https://coding-grandpa.tistory.com/entry/%ED%94%84%EB%A1%9C%EA%B7%B8%EB%9E%98%EB%A8%B8%EC%8A%A4-%EC%A0%84%ED%99%94%EB%B2%88%ED%98%B8-%EB%AA%A9%EB%A1%9D-%ED%95%B4%EC%8B%9C-Lv-2-%EC%9E%90%EB%B0%94-Java

 

[프로그래머스] 전화번호 목록 (해시 Lv. 2) - 자바 Java

0. 동일 유형 문제 [프로그래머스] 완주하지 못한 선수 (해시 Lv. 1) [프로그래머스] 전화번호 목록 (해시 Lv. 2) [프로그래머스] 위장 (해시 Lv. 2) [프로그래머스] 베스트 앨범 (해시 Lv. 3) Youtube 영

coding-grandpa.tistory.com

 

※. 정렬로 풀 때 substring 대신 startsWith 사용해도 된다.

 


정렬

import java.util.Arrays;
class Solution {
    public boolean solution(String[] phone_book) {
        boolean answer = true;
        Arrays.sort(phone_book);
        for(int i = 1; i < phone_book.length; i++) {
        	if(phone_book[i].length() >= phone_book[i-1].length()) {
	        	String temp = phone_book[i].substring(0,phone_book[i-1].length());
	        	if(temp.equals(phone_book[i-1])) {
	        		answer = false;
	        		break;
	        	}
        	}
        }
        return answer;
    }
}

해시

import java.util.HashSet;
class Solution {
    public boolean solution(String[] phone_book) {
        boolean answer = true;
        HashSet<String> hashset = new HashSet<>();
        for(int i = 0; i < phone_book.length; i++) {
            hashset.add(phone_book[i]);
        }
        
        for(int i = 0; i < phone_book.length; i++) {
            for(int j = 1; j < phone_book[i].length(); j++) {
                if(hashset.contains(phone_book[i].substring(0,j))) {
                    answer = false;
                }
            }
        }
        return answer;
    }
}