c++ - 使用 BIT Manipulation 检查两个字符串中是否有公共(public)子字符串

标签 c++ bit-manipulation substring

下面的代码用于检查两个字符串是否有公共(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/

相关文章:

c++ - 为什么data()和c_str()返回的是char const*,而operator[]返回的是char&?

c++ - 行外成员定义的类型说明符中可以省略 typename 吗?

c++ - 为什么 ofstream 不触发 IN_CREATE

c++ - 在一个序列中找到相似的数字并记录最大连续连胜

substring - Squeak(smalltalk) subSrings 忽略字符串末尾的空字符串

PHP MySQL 不使用子字符串执行更新

c - 了解此函数中的位运算

java - Java中的位运算类

c - AVX512 - 如何将所有设置位向右移动?

javascript - 在 JS 中查找字符串中的关键字