private static int[] scores;
private static int[] extCnt;
private static Map<String, List<Integer>> extUrl;
private static Map<Integer, String> url;
public static int solution(String word, String[] pages) {
scores = new int[pages.length];
extCnt = new int[pages.length];
int answer = 0;
double score = 0;
extUrl = new HashMap<>();
url = new HashMap<>();
word = word.toLowerCase();
for (int i = 0; i < pages.length; i++) {
String page = pages[i].toLowerCase();
init(page, word, i);
}
for (int i = 0; i < scores.length; i++) {
double scoreNow = scores[i];
if (extUrl.containsKey(url.get(i))) {
for (int extIdx : extUrl.get(url.get(i))) {
scoreNow += (double) scores[extIdx] / (double) extCnt[extIdx];
}
}
if (score < scoreNow) {
answer = i;
score = scoreNow;
}
}
return answer;
}
public static void init(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 curUrl = page.substring(urlStart, urlEnd);
url.put(index, curUrl);
String[] aHerf = page.split("<a href=\"");
for (int a = 1; a < aHerf.length; a++) {
String linkedUrl = aHerf[a].substring(0, aHerf[a].indexOf("\""));
if (!extUrl.containsKey(linkedUrl))
extUrl.put(linkedUrl, new ArrayList<>());
extUrl.get(linkedUrl).add(index);
}
extCnt[index] = aHerf.length - 1;
page = page.replaceAll("[^a-zA-Z]", " ");
scores[index] = countWord(page.split(" "), word);
}
public static int countWord(String[] words, String word) {
int cnt = 0;
for (String w : words) {
if (w.equals(word))
cnt++;
}
return cnt;
}