[프로그래머스/C++]Lv.2 - 뉴스 클러스터링

YH J·2023년 9월 24일
0

프로그래머스

목록 보기
154/168

문제 링크

https://school.programmers.co.kr/learn/courses/30/lessons/17677

내 풀이

str1과 2에서 알파벳2개로 나올수 있는 모든 경우를 구한다.
공집합의 예외처리를 해둔다.
합집합을 구하기 위해 미리 all에 str1vec, str2vec의 크기를 더해둔다.
str1vec의 원소를 str2vec에서 찾아가면서 있으면 str2vec에서 지운다.
구한 교집합을 all에서 뺀 뒤 교집합/합집합 * 65536을 계산한다.

내 코드

#include <string>
#include <vector>
#include <cctype>
#include <algorithm>
using namespace std;

int solution(string str1, string str2) {
    int answer = 0;
    
    vector<string> str1vec;
    vector<string> str2vec;
    
    for(int i = 0; i < str1.length() - 1; i++)
    {
        if(isalpha(str1[i]) && isalpha(str1[i+1]))
        {
            string s;
            s += tolower(str1[i]);
            s += tolower(str1[i+1]);
            str1vec.push_back(s);
        }
    }
    
    for(int i = 0; i < str2.length() - 1; i++)
    {
        if(isalpha(str2[i]) && isalpha(str2[i+1]))
        {
            string s;
            s += tolower(str2[i]);
            s += tolower(str2[i+1]);
            str2vec.push_back(s);
        }
    }
    
    if(str1vec.empty() && str2vec.empty())
        return 65536;
    
    double cross = 0;
    double all = 0;
    
    all = str1vec.size() + str2vec.size();
    
    for(string s : str1vec)
    {
        auto iter = find(str2vec.begin(), str2vec.end(), s);
        if(iter != str2vec.end())
        {
            cross++;
            str2vec.erase(iter);
        }
    }
    all -= cross;
    return (int)(cross/all * 65536);
}

다른 사람의 풀이

#include <bits/stdc++.h>
using namespace std;
short a, b, C[676], D[676];
int solution(string A, string B) {
    for(int i=1; i<A.size(); i++)
        if(isalpha(A[i-1]) && isalpha(A[i]))
            C[(A[i-1]&31)*26+(A[i]&31)]++;
    for(int i=1; i<B.size(); i++)
        if(isalpha(B[i-1]) && isalpha(B[i]))
            D[(B[i-1]&31)*26+(B[i]&31)]++;
    for(int i=0; i<676; i++) a+=min(C[i], D[i]), b+=max(C[i], D[i]);
    return b ? a*65536/b : 65536;
}

다른 사람의 풀이 해석

26개의 알파벳 2개로 나올 수 있는 모든 경우의 수의 개수만큼 배열을 선언해둔다.
알파벳 2개의 조합을 모두 숫자로 바꿔서 배열에 저장한다.
교집합은 두 배열에서 min값을, 합집합은 max 값을 더한다.

profile
게임 개발자 지망생

0개의 댓글