String三姐妹

1,java String类 --字符串常量

简要的说,string类型和stringbuffer类型的主要性能区别在于string是不可变的对象(每次改变字符串,会在字符串常量池中声明一个新的字符串常量,来替代原来内存地址指向的字符串常量,原来的字符串常量并不会消失,大量浪费内存空间),因为每次生产对象都会对系统性能产生影响,特别是当 内存中无引用对象(没有用到的字符串常量)多了以后,JVM的GC垃圾回收就会开始工作,那速度就慢下来了。

2,stringBuffer

线程安全的,有线程锁,底层是一个char数组,默认长度为16,大量使用拼接且注意线程安全的时候用此类。

stringbuffer底层是一个数组,每次进行拼接,会直接copy当前string类的数组,赋值给stringbuffer对象。调用tostring方法返回string字符串。

3,StringBuilder

stringbuilder是线程不安全的,没有锁。底层实现和stringbuffer基本相同。

效率比stringbuffer高,线程不安全。

  	 	String a="c";
        String b="b";
        String c=a+b;//底层调用stringbuilder的append方法进行拼接,
        String d="c"+"b";//存在于字符长常量池中
        System.out.println(c==d);//c是堆中的对象地址,d是字符串常量池中的常量地址。所以返回false

注意事项:

双引号常量进行拼接,会在常量池中新建一个字符串常量。

而字符串对象拼接,由于底层会调用stringbuilder类的append方法进行拼接,会在堆内存中开辟一个对象,指向该对象。

所以,即使两个值是一样,用==比较时,也会返回false

#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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值