본문 바로가기
카카오 코딩 테스트 풀이

매칭 점수 풀이

by paysmile 2019. 9. 4.
#include <string>
#include <vector>
#include <map>

using namespace std;
const int MAX = 20;

map<string, int> page;
vector <pair<int, pair<int, vector<string>>>> info;
vector<pair<int, double>> matching;

char uppertolower(char a) {
	if (a >= 'A' && a <= 'Z')
		a = a - 'A' + 'a';
	return a;
}

int solution(string word, vector<string> pages) {
	int answer = 0;

	for (int i = 0; i < word.size(); i++) {
		word[i] = uppertolower(word[i]);
	} 
	for (int i = 0; i < pages.size(); i++) {
		string html = pages[i];
		int start = 0, last = 0, loc;

		start = html.find("<meta") + 5;
		html = html.substr(start);
		last = html.find("/>");
		loc = html.find("https://");

		if (loc > last)
			continue;

		start = html.find("https://") + 8;
		string str = "";
		while (start != (last-1)) {
			str = str + html[start];
			start++;
		}
		page[str] = i;

		html = html.substr(html.find("<body") +5);
		string cache = html;
		last = html.find("/body>");
		bool inbrace = true;
		start = html.find(">");
		int index = html.find(">") + 1;
		int counts = 0, answer = 0;
		while (index < last) {
			if (html[index] == '<')
				inbrace = false;
			if (!inbrace) {
				if (html[index] == '>') 
					inbrace = true;
			}
			else {
				if (counts == word.size() && !(uppertolower(html[index]) >= 'a' && uppertolower(html[index]) <= 'z') )
					answer++;
				if (uppertolower(html[index]) == word[counts])
					counts++;
				else
					counts = 0;
			}
			index++;
		}

		vector<string> exturl;
		int cachestart = cache.find("<a href") + 7;
		while (cachestart != string::npos && cachestart < last) {
			cache = cache.substr(cachestart);
			cache = cache.substr(cache.find("https://") + 8);
			exturl.push_back(cache.substr(0, cache.find("\"")));
			cachestart = cache.find("<a href");
		}
		info.push_back(make_pair(i, make_pair(answer, exturl)));
		html = html.substr(last + 6);
	}

	for (int i = 0; i < page.size(); i++)
		matching.push_back(make_pair(i, 0));

	for (int i = 0; i < page.size(); i++) {
		double answer;
		string urls;
		matching[i].second += info[i].second.first;
		answer = (double)info[i].second.first / (double)info[i].second.second.size();
		for (int j = 0; j < info[i].second.second.size(); j++) {
			string urls = info[i].second.second[j];
			if (page.find(urls) == page.end())
				continue;
			matching[page[urls]].second += answer;
		}
	}

	answer = matching[0].first;
	double minvalue = matching[0].second;
	for (int i = 1; i < matching.size(); i++) {
		if (matching[i].second > minvalue) {
			minvalue = matching[i].second;
			answer = matching[i].first;
		}
	}
	return answer;
}

20개의 테스트 중, 1개의 테스트를 실패하는데 그 이유를 아직 못찾았다...

'카카오 코딩 테스트 풀이' 카테고리의 다른 글

순위 검색 C++  (0) 2021.03.16
신규 아이디 C++  (0) 2021.03.14
길 찾기 게임 풀이  (0) 2019.09.03
무지의 먹방 라이브  (0) 2019.09.02
후보키 풀이  (0) 2019.09.02