版权声明:我的GitHub:https://github.com/617076674。真诚求星! https://blog.csdn.net/qq_41231926/article/details/84918684
我的数据结构与算法题目集代码仓:https://github.com/617076674/Data-structure-and-algorithm-topic-set
原题链接:https://pintia.cn/problem-sets/15/problems/891
题目描述:
知识点:字符串、set集合的应用
思路:用getchar()函数一个一个字符地读取并分隔
将每个文件读取到的单词都放进一个set集合里,查询时遍历其中一个set集合的所有元素,在另一个set集合里查找,如果找到,则相同字符数common加1,总字符数为两个set集合之和减去common。
时间复杂度与空间复杂度和输入的数据有关。
C++代码:
#include<iostream>
#include<string>
#include<set>
using namespace std;
set<string> sets[100];
int main() {
int N;
scanf("%d", &N);
getchar();
for(int i = 0; i < N; i++) {
string str = "";
while(true) {
char c = getchar();
if(c == '#') {
break;
} else if((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {
if(c >= 'a' && c <= 'z') {
c = c - 'a' + 'A';
}
str += c;
} else {
if(str.length() >= 3) {
if(str.length() > 10){
str = str.substr(0, 10);
}
sets[i].insert(str);
}
str = "";
}
}
}
int M;
scanf("%d", &M);
for(int i = 0; i < M; i++) {
int num1, num2;
scanf("%d %d", &num1, &num2);
int common = 0;
for(set<string>::iterator it = sets[num1 - 1].begin(); it != sets[num1 - 1].end(); it++){
if(sets[num2 - 1].find(*it) != sets[num2 - 1].end()){
common++;
}
}
int total = sets[num1 - 1].size() + sets[num2 - 1].size() - common;
printf("%.1f%\n", common * 100.0 / total);
}
return 0;
}
C++解题报告:
扫描二维码关注公众号,回复:
4757178 查看本文章