LeetCode318. Maximum Product of Word Lengths

题意

  • 给一个字符串数组, 求其中两个字符完全不同的串的长度乘积

方法

  • 位运算

代码

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

你可能感兴趣的:(hot,100,算法,数据结构,c++)