231006 메뉴 리뉴얼

Jongleee·2023년 10월 6일
0

TIL

목록 보기
383/737
private List<String> answerList;
private Map<String, Integer> hashMap;

public String[] solution(String[] orders, int[] course) {
	answerList = new ArrayList<>();
	hashMap = new HashMap<>();
	preprocessOrders(orders);
	generateCombinations(orders, course);
	return getAnswer();
}

private void preprocessOrders(String[] orders) {
	for (int i = 0; i < orders.length; i++) {
		char[] arr = orders[i].toCharArray();
		Arrays.sort(arr);
		orders[i] = String.valueOf(arr);
	}
}

private void generateCombinations(String[] orders, int[] course) {
	for (int courseLength : course) {
		for (String order : orders) {
			generateCombination("", order, courseLength);
		}
		checkAndAddValidCombinations();
		hashMap.clear();
	}
}

private void generateCombination(String current, String remaining, int count) {
	if (count == 0) {
		hashMap.put(current, hashMap.getOrDefault(current, 0) + 1);
		return;
	}

	for (int i = 0; i < remaining.length(); i++) {
		generateCombination(current + remaining.charAt(i), remaining.substring(i + 1), count - 1);
	}
}

private void checkAndAddValidCombinations() {
	if (!hashMap.isEmpty()) {
		int maxFrequency = Collections.max(hashMap.values());

		if (maxFrequency > 1) {
			for (Map.Entry<String, Integer> entry : hashMap.entrySet()) {
				if (entry.getValue() == maxFrequency) {
					answerList.add(entry.getKey());
				}
			}
		}
	}
}

private String[] getAnswer() {
	Collections.sort(answerList);
	return answerList.toArray(new String[0]);
}

출처:https://school.programmers.co.kr/learn/courses/30/lessons/72411

0개의 댓글