leetcode 318. 最大单词长度乘积

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/L1558198727/article/details/88902567
利用26位二进制来存储一个字符是否含有该字母
之后判断两个字符串的交集只需做位与操作
#include <iostream>
#include <string>
#include <vector>
using namespace std;

class Solution {
public:
    int maxProduct(vector<string>& words) {
        vector<int> bit(words.size());
        for(int i=0;i<words.size();i++){
            for(int  j=0 ; j< words[i].size();j++){
                bit[i] |= 1<<( words[i][j] - 'a' );
            }
        }
        int len = 0;
        for(int i=0;i<words.size();i++){
            for(int j=i+1;j<words.size();j++){
                if(!(bit[i]&bit[j]) ){
                    len = max(len, (int)words[i].size() * (int)words[j].size());
                }
            }
        }
        return len;
    }
};

int main()
{
    Solution Solution1;
    string a[6] = {"abcw","baz","foo","bar","xtfn","abcdef"};
    vector<string> aa(a,a+6);
    cout<<Solution1.maxProduct(aa)<<endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/L1558198727/article/details/88902567