检查使用BIT操作的两个字符串中是否有共同的子字符串

Check if there is a common substring in two strings using BIT Manipulation

本文关键字:字符串 是否 两个 BIT 操作 检查      更新时间:2023-10-16

以下代码用于检查两个字符串是否有共同的子字符串,如果有共同的子字符串则打印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"。