231201 매칭 점수

Jongleee·2023년 12월 1일
0

TIL

목록 보기
431/737
private int[] scores;
private int[] externalCnt;
private Map<String, List<Integer>> externalUrl;
private Map<Integer, String> url;

public int solution(String word, String[] pages) {
	initializeDataStructures(pages.length);
	word = word.toLowerCase();

	for (int i = 0; i < pages.length; i++) {
		String page = pages[i].toLowerCase();
		setUrl(page, word, i);
	}

	return calculatePageRank();
}

private void initializeDataStructures(int size) {
	scores = new int[size];
	externalCnt = new int[size];
	externalUrl = new HashMap<>();
	url = new HashMap<>();
}

private void setUrl(String page, String word, int index) {
	String urlPattern = "<meta property=\"og:url\" content=\"";
	int urlStart = page.indexOf(urlPattern) + urlPattern.length();
	int urlEnd = page.indexOf("\"/>", urlStart);
	String currentUrl = page.substring(urlStart, urlEnd);
	url.put(index, currentUrl);

	String[] aHerf = page.split("<a href=\"");
	for (int a = 1; a < aHerf.length; a++) {
		String linkedUrl = aHerf[a].substring(0, aHerf[a].indexOf("\""));
		externalUrl.computeIfAbsent(linkedUrl, k -> new ArrayList<>()).add(index);
	}

	externalCnt[index] = aHerf.length - 1;

	page = page.replaceAll("[^a-zA-Z]", " ");
	scores[index] = countWord(page.split(" "), word);
}

private int countWord(String[] words, String word) {
	int cnt = 0;
	for (String w : words) {
		if (w.equals(word)) {
			cnt++;
		}
	}
	return cnt;
}

private int calculatePageRank() {
	int answer = 0;
	double maxScore = 0;

	for (int i = 0; i < scores.length; i++) {
		double scoreNow = scores[i];

		if (externalUrl.containsKey(url.get(i))) {
			for (int extIdx : externalUrl.get(url.get(i))) {
				scoreNow += (double) scores[extIdx] / (double) externalCnt[extIdx];
			}
		}

		if (maxScore < scoreNow) {
			answer = i;
			maxScore = scoreNow;
		}
	}

	return answer;
}

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

0개의 댓글