String 三姐妹

本文详细解析了String类的特点,包括其不可变性和final属性,探讨了StringBuffer与StringBuilder的区别,特别是它们在线程安全性上的不同。

String类是final的,一断创建后就不能更改,因此对于String对象的各种操作都是生成了一个新的String 对象

StringBuffer类:当频繁修改字符串内容的时候建议使用该类,
该类 是线程安全的
StringBuilder 是 StringBuffer 的一个双胞胎 但是他是线程不安全的。

#include <iostream> #include <vector> #include <map> #include <set> #include <queue> #include <string> using namespace std; struct Person { char gender; string father; string mother; }; map<string, Person> persons; // 获取某人五代以内的所有祖先(包含父母、祖父母... 最多上溯5层) set<string> getAncestorsWithin5(const string& id) { set<string> ancestors; if (id == "-1") return ancestors; // BFS: {current_id, depth},depth 表示离当前人的代数(0表示自己,1表示父母,2祖父母...最大5) queue<pair<string, int>> q; q.push({id, 0}); while (!q.empty()) { auto [cur, depth] = q.front(); q.pop(); if (depth >= 5) continue; // 超过五代不再追溯 const auto& p = persons[cur]; // 父亲 if (p.father != "-1") { ancestors.insert(p.father); q.push({p.father, depth + 1}); } // 母亲 if (p.mother != "-1") { ancestors.insert(p.mother); q.push({p.mother, depth + 1}); } } return ancestors; } int main() { int N; cin >> N; for (int i = 0; i < N; ++i) { string id, fa, ma; char gen; cin >> id >> gen >> fa >> ma; persons[id] = {gen, fa, ma}; } int K; cin >> K; for (int i = 0; i < K; ++i) { string a, b; cin >> a >> b; // 规则1:同性不能结婚 if (persons[a].gender == persons[b].gender) { cout << "Never Mind" << endl; continue; } // 获取两人五代以内的祖先集合 set<string> ancA = getAncestorsWithin5(a); set<string> ancB = getAncestorsWithin5(b); // 判断是否有共同祖先在五代以内 bool hasCommon = false; for (const auto& ancestor : ancA) { if (ancB.count(ancestor)) { hasCommon = true; break; } } if (hasCommon) { cout << "No" << endl; } else { cout << "Yes" << endl; } } return 0; }运行过后只会输出no
最新发布
11-18
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值