본문 바로가기

알고리즘/프로그래머스

(5)
스택/큐 #1 쇠막대기 - JAVA class Solution { public int solution(String arrangement) { int answer = 0; int stack = 0; boolean frontOpen = false; for (byte b : arrangement.getBytes()) { if (b==40) { stack++; frontOpen = true; } else { stack--; if (frontOpen) { answer += stack; } else { answer++; } frontOpen = false; } } return answer; } }
해시 #4 베스트앨범 - JAVA import java.util.*; class Solution { public int[] solution(String[] genres, int[] plays) { int[] answer = {}; HashMap genresRank = new HashMap(); HashMap genresTop2 = new HashMap(); for (int i = 0; i < genres.length; i++) { //장르기준 랭크 측정 genresRank.put(genres[i], genresRank.getOrDefault(genres[i], 0) + plays[i]); int[] value = {-1, -1}; //장르별 top2 선정 if (genresTop2.containsKey(genres[i])) { int[]..
해시 #3 위장 - JAVA import java.util.HashMap; class Solution { public int solution(String[][] clothes) { int answer = 1; HashMap clothesHash = new HashMap(); for (String[] cloth : clothes) clothesHash.put(cloth[1], clothesHash.getOrDefault(cloth[1], 0) + 1); for (String key : clothesHash.keySet()) { answer *= (clothesHash.get(key) + 1); } answer -= 1; return answer; } } 각 종류에따른 HashMap을 구성하고 경우의 수를 구한다. 이때, 입지 않는 경..
해시 #2 전화번호 목록 - JAVA import java.util.*; class Solution { public boolean solution(String[] phone_book) { Arrays.sort(phone_book); for (int i = 1; i < phone_book.length; i++) { if (phone_book[i].startsWith(phone_book[i-1])) { return false; } } return true; } } startsWith(string) 앞에 해당 string으로 시작하면 true, 아니면 false를 반환한다. 일단 sorting 시키고 앞에꺼랑 비교하면서 진행한다. 이미 정렬한 상태이기 때문에 앞에랑도 다른데 그 앞이랑은 다를 수가 없다. class Solution { public..
해시 #1 완주하지 못한 선수 - JAVA import java.util.*; class Solution { public String solution(String[] participant, String[] completion) { Arrays.sort(participant); Arrays.sort(completion); int i; for ( i=0; i