面试题:将字符串s1中所有出现在字符串s2中的字符删除
ps:代码已经修改,本地简单测了一下没问题。
返回一个新的字符串,不要使用set,map等。
没有搜到很好的解答,贴一个自己当时的思路,抛砖引玉。
(面试官没让运行,大家看思路为主,可能有错误)
//字符串过滤,返回值string
//将s1中在s2中重复出现的字符去掉
//位运算模拟set
string myFilter1(string s1, string s2) {
//存储结果
string res;
if (s1.empty() || s2.empty()) {
res = s1;
return res;
}
//记录s2中的字符
vector<int> mySet(4);
for (auto& ch : s2) {
int idx = ch / 32;
mySet[idx] |= (1 << (ch % 32));
}
for (auto& ch : s1) {
int idx = ch / 32;
//只拷贝s2中没有出现的字符
if (!(mySet[idx] & (1 << (ch % 32)))) {
res.push_back(ch);
}
}
return res;
}
查看16道真题和解析