본문 바로가기

컴퓨터/프로그래머스

프로그래머스 - 131127번: 할인 행사 [Java]

문제: https://school.programmers.co.kr/learn/courses/30/lessons/131127

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

1. 코드

import java.util.*;
class Solution {
    public int solution(String[] want, int[] number, String[] discount) {
        int answer = 0;
        Map <String, Integer> map = new HashMap<>();
            for(String w : want)
                map.put(w, 0);
        
        for(int i = 0; i <= discount.length - 10; i++) {
            Map <String, Integer> temp = new HashMap<>();
            temp.putAll(map);
            boolean flag = true;
            for(int j = i; j < i + 10; j++) {
                if(!temp.containsKey(discount[j])) {
                    flag = false;
                    break;
                }
                temp.put(discount[j], temp.get(discount[j]) + 1);
            }
            if(!flag) continue;

            for(int j = 0; j < want.length; j++) {
                if(temp.get(want[j]) < number[j]) {
                    flag = false;
                    break;
                }
            }
            if(flag) answer++;
        }
        return answer;
    }
}

2. 설명

HashMap을 사용하여 할인행사 물품을 입력받으면 1씩 증가시켜서 want와 동일한지 확인 후 동일하다면 종료합니다.

3. 정리

  1. HashMap을 이용하여 문자열 인덱스를 손쉽게 구한다.
출처: 프로그래머스 코딩 테스트 연습, 
https://school.programmers.co.kr/learn/challenges