Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | |||||
3 | 4 | 5 | 6 | 7 | 8 | 9 |
10 | 11 | 12 | 13 | 14 | 15 | 16 |
17 | 18 | 19 | 20 | 21 | 22 | 23 |
24 | 25 | 26 | 27 | 28 | 29 | 30 |
31 |
Tags
- 알고리즘
- 백준
- 프로그래머스
- map
- DP
- 백트래킹
- 깊이우선탐색
- DFS
- stoi
- Set
- 에라토스테네스의 체
- BFS
- C++
- int
- 이분탐색
- priority_queue
- 분할정복
- 우선순위큐
- 티스토리챌린지
- 다이나믹프로그래밍
- 오블완
- 유클리드호제법
- N과M
- 정렬
- 배열
- vector
- 최소공배수
- 그래프
- Sort
- 문자열
Archives
- Today
- Total
안녕 세상아,
[프로그래머스/c++] Lv2 [1차] 뉴스 클러스터링 (vector 사용) 본문
https://school.programmers.co.kr/learn/courses/30/lessons/17677
프로그래머스
SW개발자를 위한 평가, 교육, 채용까지 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프
programmers.co.kr
1. 영문자로 된 글자 쌍 추출 함수
1-1) 소문자로 바꾸기
2. 교집합 개수 구하기 (중복 허용)
3. 65536 곱한 후 소수점 아래 버림
#include <string>
#include <vector>
#include <algorithm>
#include <cctype>
using namespace std;
// 문자열에서 문자 쌍 추출
vector<string> extracts_vector(string s) {
vector<string> pairs;
for (int i = 0; i < s.size() - 1; i++) {
char first = tolower(s[i]);
char second = tolower(s[i + 1]);
if (isalpha(first) && isalpha(second)) {
pairs.push_back(string{first, second});
}
}
return pairs;
}
// 자카드 유사도 계산
int solution(string str1, string str2) {
vector<string> v1 = extracts_vector(str1);
vector<string> v2 = extracts_vector(str2);
// 정렬
sort(v1.begin(), v1.end());
sort(v2.begin(), v2.end());
// 교집합 크기 계산 (중복 반영)
int interCnt = 0;
int i = 0, j = 0;
while (i < v1.size() && j < v2.size()) {
if (v1[i] == v2[j]) {
interCnt++; // 공통 원소 발견
i++;
j++;
} else if (v1[i] < v2[j]) {
i++; // v1 쪽이 작으면 이동
} else {
j++; // v2 쪽이 작으면 이동
}
}
// 합집합 크기 계산
int unionCnt = v1.size() + v2.size() - interCnt;
// 자카드 유사도 계산
double jaccard = (unionCnt == 0) ? 1.0 : static_cast<double>(interCnt) / unionCnt;
// 결과 반환
return static_cast<int>(jaccard * 65536);
}
'프로그래머스' 카테고리의 다른 글
[프로그래머스/c++] Lv1 옹알이(2) (0) | 2025.01.04 |
---|---|
[프로그래머스/c++] Lv2 타겟 넘버 (0) | 2024.12.29 |
[프로그래머스/c++] Lv2 튜플 (1) | 2024.12.15 |
[프로그래머스/c++] Lv2 게임 맵 최단거리 (1) | 2024.11.15 |
[프로그래머스/c++] Lv1 덧칠하기 (0) | 2024.11.06 |