[2021.03.31] 코딩테스트 준비

web comdori·2021년 3월 30일
0

2018 코딩테스트 문제 5번 풀이

  • set_union, set_intersection 이전에 sort 필요함!
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>

using namespace std;

void capitalize(string& str)
{
	for (auto& c : str)
		c = toupper(c);
}

bool is_text(char c)
{
	if ((c >= 'A') && (c <= 'Z'))
		return true;
	return false;
}

void getVect(string& str, vector<string> &strVect)
{
	for (int i = 0; i < str.size() - 1; i++) {
		// 둘 다 대문자
		if (is_text(str[i]) && is_text(str[i+1])) {
			strVect.push_back({ str[i], str[i + 1], '\0' });
		}
	}
}

int getInterSize(vector<string>& str1Vect, vector<string>& str2Vect)
{
	vector<string> buff(str1Vect.size() + str2Vect.size());

	sort(str1Vect.begin(), str1Vect.end());
	sort(str2Vect.begin(), str2Vect.end());

	auto iter = set_intersection(
		str1Vect.begin(), str1Vect.end(),
		str2Vect.begin(), str2Vect.end(),
		buff.begin());
	buff.erase(iter, buff.end());

	return buff.size();
}

int getUniSize(vector<string>& str1Vect, vector<string>& str2Vect)
{
	vector<string> buff(str1Vect.size() + str2Vect.size());

	sort(str1Vect.begin(), str1Vect.end());
	sort(str2Vect.begin(), str2Vect.end());

	auto iter = set_union(str1Vect.begin(), str1Vect.end(),
		str2Vect.begin(), str2Vect.end(), buff.begin());
	buff.erase(iter, buff.end());

	return buff.size();
}

int solution(string str1, string str2)
{
	double answer = 0;

	capitalize(str1);
	capitalize(str2);

	vector<string> str1Vect, str2Vect;

	getVect(str1, str1Vect);
	getVect(str2, str2Vect);

	double interSize = getInterSize(str1Vect, str2Vect);
	double uniSize = getUniSize(str1Vect, str2Vect);

	if ((interSize == 0) && (uniSize == 0)) {
		answer = 1;
	}
	else {
		answer = interSize / uniSize;
	}

	return int(answer * 65536);
}

int main()
{
	string str1 = "aa1+aa2";
	string str2 = "AAAA12";

	int answer = solution(str1, str2);

	cout << answer << endl;

	return 0;
}
profile
(wanna be a) Full-Stack Engineer

0개의 댓글