下面的代码用于检查两个字符串是否有公共(public)子串,如果有公共(public)子串则打印YES,如果没有公共(public)子串则打印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++ - 使用 BIT Manipulation 检查两个字符串中是否有公共(public)子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38056497/