检查使用BIT操作的两个字符串中是否有共同的子字符串
Check if there is a common substring in two strings using BIT Manipulation
以下代码用于检查两个字符串是否有共同的子字符串,如果有共同的子字符串则打印YES,如果没有共同的子字符串则打印NO。7号线到底是做什么的?请解释。
1 #include<iostream>
2 using namespace std;
3
4 int letterBits(const string &s) {
5 int bits = 0;
6 for (char ch : s)
7 bits |= 1 << (ch - 'a');
8 return bits;
10 }
11
12 int main() {
13 int testCases;
14 cin >> testCases;
15 while (testCases--) {
16 string strA, strB;
17 cin >> strA >> strB;
18 int bitsA = letterBits(strA);
19
20 int bitsB = letterBits(strB);
21 cout<<bitsB<<" ";
22 cout << (bitsA & bitsB ? "YES": "NO") << endl;
23 }
24 return 0;
25 }
第7行为它找到的每个字母设置一个整数位。(例如,如果字母是'a',设置位0,如果字母是'b',设置位1,等等)
这个方法只检查两个字符串是否有相同的字母,所以"abc"=="cba"。
相关文章:
- C++-字符串是否包含一个带有简单循环的单词
- 将常量字符串添加到非常量字符串是否会给出常量字符串
- 检查字符串是否"null" C++
- 使用XOR查找O(n)-解决方案中的两个字符串是否为变位符
- 检查字符串是否为整数
- 使用 SET(C++) 检查两个给定字符串是否是字谜时出现运行时错误
- 如何检查字符串是否正确以将其转换为 int?
- 程序检查字符串是否只包含 1 和 0?
- 检查字符串是否是拉平德罗姆
- 尝试使用 indexOf 创建一个 if 语句来检查字符串是否包含字符.有一点麻烦
- 通过默认复制构造函数比较 C++ 字符串是否会影响性能,原因为何?
- gtest:检查字符串是否等于两个字符串之一
- 如何检查字符串是否包含所有这些:数字、字母和特殊字符
- 如何检查字符串是否以C++中的"ed"结尾;
- 字符串是否在其构造函数中复制数据
- 检查字符串是否是数字,然后将该数字转换为 int?
- 如何检查一个字符串是否包含多个其他字符串?
- 检查字符串是否仅包含字母
- 如何根据一个特定字母的出现来确定两个字符串是否相等?
- 查找字符串是否包含字符串向量的任何一个元素的最佳方法