삽질메모장

programmers : hash 2 (전화번호 목록)[java] 본문

Knowledge/알고리즘

programmers : hash 2 (전화번호 목록)[java]

shovel 2022. 1. 11. 16:10

119, 11923 이라는 두개의 정수를 포함하는 phone_book[]이 있다면

첫번째 반복(i=0) 에서 containskey( substring[0,3])이라면 "119"이기때문에 모든 경우가 containskey되는것이라 생각되어서 j-1 아닌가? 했었다.

 

실제로는 substring(begin index, end index)에서 end index 는 해당 index의 바로 앞까지만 자른다

즉 phone_book[0] = 119이라면 phone_book[0].substring(0,3) == 11 인것이다. 

이런 헷갈리는 부분만 없으면 금방풀수있는 쉬운 문제이다.

import java.util.HashMap; 
import java.util.Map;
class Solution {
    public boolean solution(String[] phone_book) {
        Map<String, Integer> map = new HashMap<>();
        
        for(int i= 0; i<phone_book.length; i++)
            map.put(phone_book[i], i);
        
        for(int i=0; i<phone_book.length; i++)
            for(int j =0; j<phone_book[i].length(); j++)
                if(map.containsKey(phone_book[i].substring(0, j)))
                    return false;
    return true;
    }
}