본문 바로가기

Algorithm

[알고리즘]프로그래머스 - 해시

1. 완주하지 못한 선수

import java.util.*;

class Solution {
    public String solution(String[] participant, String[] completion) {
        String answer = "";
        Map<String,Integer> map = new HashMap<>();
        for(String values: participant){
            map.putIfAbsent(values,0);
            map.put(values,map.get(values)+1);
        }
        for(String values: completion){
            map.put(values,map.get(values)-1);
        }
        for(String keys : map.keySet()){
            if(map.get(keys) == 1){
                return keys;
            }
        }
        return answer;
    }
}

Map을 활용하면, 쉽게 배열에 담긴 값의 갯수를 셀 수 있고

두 개의 배열을 쉽게 비교할 수 있다. 

 

2. 전화번호 목록

import java.util.*;

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

 startWith를 처음 사용 해봐서 해시를 이용하지 않고 작성해보았다. 

 

import java.util.*;

class Solution {
    boolean answer = true;
    public boolean solution(String[] phone_book) {
        int min=Integer.MAX_VALUE;
        HashMap<String,Integer> resultHash = new HashMap();
        for(int i=0; i<phone_book.length; i++) {
            min = Math.min(min, phone_book[i].length());
        }
        for(int i=0; i<phone_book.length;i++) {
            String headerText = phone_book[i].substring(0,min);
            resultHash.putIfAbsent(headerText,0);
            resultHash.put(headerText,resultHash.get(headerText)+1);
        }
        resultHash.forEach((key,value)->{
            if(value>1) {
                answer = false;
            }
        });
        return answer;
    }
}

일단 배열에서 제일 작은 값을 찾고

그 크기만큼만 substring메소드를 활용하여 문자열을 뽑아낸다.

뽑아낸 문자열은 Map에 하나씩 쌓아올린다.

 

쌓아올린 Map에서

foreach 와 람다식을 활용하여

중복된 값이 있을 시에

answer을 false값으로 바꾼다.

 

3. 위장

import java.util.*;
class Solution {
    int answer = 1;
    public int solution(String[][] clothes) {
        Map<String,Integer> map = new HashMap<>();
        for(String[] value : clothes){
            map.putIfAbsent(value[1],0);
            map.put(value[1],map.get(value[1])+1);
        }
        map.forEach((key,value)->{
          answer = answer*(value+1);
        });
       return answer-1;
    }
}

 경우의 수를 따지기 위해 조합(순열)을 이용하여 따졌다.

n = (q+1) * (w+1) * (e+1) .. -1