티스토리 뷰

algorithm

[algorithm] 전화번호 목록

tonirr 2021. 4. 3. 18:57
import java.util.HashMap;
import java.util.Map;

class Solution {
        public boolean solution(String[] phone_book) {
        boolean answer = true;
        Map<String, Integer> map = new HashMap<String, Integer>();
        for(int i=0; i<phone_book.length; i++) {
        	map.put(phone_book[i], i);
        }
        
        for(int i=0; i<phone_book.length; i++) {
        	
        	int phoneLength = phone_book[i].length();
        	for(String phone: map.keySet()) {
        		String post_phone="";
        		if(phoneLength<phone.length()) {
        			post_phone = phone.substring(0, phoneLength);
        		}            	
        		if(phone_book[i].equals(post_phone) && i!=map.get(phone)) {
            		answer = false;
            		return answer;
            	}
            }
        }        
        return answer;
    }
}

import java.util.HashMap;
import java.util.Map;

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

class Solution {
    public boolean solution(String[] phone_book) {
        for(int i = 0; i<phone_book.length-1; i++) {
        	
        	int hashCode = phone_book[i].hashCode();
        	int len = phone_book[i].length();
        	
        	for(int j = i+1; j<phone_book.length; j++) {
            	if(phone_book[j].length() >= len 
            		&& hashCode == phone_book[j].substring(0, len).hashCode()) {	
            		return false;
            	}
            	else if(phone_book[j].length() < len 
            	    && phone_book[i].substring(0, phone_book[j].length()).hashCode() == phone_book[j].hashCode()) {
            		return false;
            	}
        	}
        }
        return true;
    }
}
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/01   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함