풀이 단계는 다음과 같다.
코드는 아래와 같다.
#include <string>
#include <map>
#include <algorithm>
using namespace std;
void parse(const string &str, vector<string> &result)
{
for(int i=0;i<str.size()-1;i++) {
if(!isalpha(str[i]))
continue;
if(!isalpha(str[i+1])) {
i++;
continue;
}
string s(2, 0);
s[0] = tolower(str[i]);
s[1] = tolower(str[i + 1]);
result.push_back(s);
}
}
map<string, int> operator+ (const map<string, int> &a, const map<string, int> &b) {
map<string, int> result;
for(auto it : a)
result[it.first] = it.second;
for(auto it : b) {
if(result.find(it.first) != result.end())
result[it.first] = max(result[it.first], it.second);
else
result[it.first] = it.second;
}
return result;
}
int get_parent(const map<string, int> &m)
{
int result = 0;
for(auto it : m)
result += it.second;
return result;
}
int get_child(const vector<string> &a, map<string, int> &m)
{
int result = 0;
for(auto it : a) {
auto entry = m.find(it);
if(entry != m.end()) {
if(entry->second != 0) {
result++;
entry->second--;
}
}
}
return result;
}
int jaccard(vector<string> s1, vector<string> s2)
{
if(s1.empty() && s2.empty())
return 65536;
map<string, int> m1;
for(auto it : s1) m1[it]++;
map<string, int> m2;
for(auto it : s2) m2[it]++;
map<string, int>m3 = m1 + m2;
int p = get_parent(m3);
int c = get_child(s1, m2);
return (int)((double)(c << 16) / (double)p);
}
int solution(string str1, string str2) {
vector<string> s1, s2;
parse(str1, s1);
parse(str2, s2);
int answer = jaccard(s1, s2);
return answer;
}