字符串是否包含问题

//假设这有两个分别由字母组成的字符串A另外字符串B,字符串B的字母数较字符串A少一些。
//什么方法能最快地查出字符串B所有字母是不是都在字符串A里?
//也就是说判断字符串B是不是字符串A的真子集(为了简化,姑且认为两个集合都不是空集,即字符串都不为空。)。为了简单起见,我们规定输入的字符串只包含大写英文字母。

//实现函数bool compare(string &A,string &B)

//int 32位,使用一个整数来hash
#include <iostream>
using namespace std;

bool compare(string &a,string &b)
{
    int hash_b=0;

    for(int i=0;i<b.length();i++) {
        hash_b|=(1<<(b[i]-'A'));
    }

    int hash_a=0;
    for(int i=0;i<a.length();i++) {
        hash_a|=(1<<(a[i]-'A'));
    }

    return hash_b==(hash_a&hash_b);
}

int main()
{
    string a("ABCDEFGHG");
    string b("BCDHGK");

    cout<<compare(a,b)<<"
";

    return 0;
}
原文地址:https://www.cnblogs.com/mr-redrum/p/3598885.html