[leetcode] 318. Maximum Product of Word Lengths

Given a string array words, find the maximum value of length(word[i]) * length(word[j]) where the two words do not share common letters. You may assume that each word will contain only lower case letters. If no such two words exist, return 0.

Example 1:

Given ["abcw", "baz", "foo", "bar", "xtfn", "abcdef"]
Return 16
The two words can be "abcw", "xtfn".

Example 2:

Given ["a", "ab", "abc", "d", "cd", "bcd", "abcd"]
Return 4
The two words can be "ab", "cd".

Example 3:

Given ["a", "aa", "aaa", "aaaa"]
Return 0
No such pair of words.

这道题是找出数组中两个 不重复字符的 字符串的长度最大乘积,题目难度为Medium。

采用两层循环遍历比对,查看字符串中字符是否重复,如果不重复计算长度乘积,比对后更新最大乘积。可以看出,题目的关键是如何比对字符串中的字符是否重复,最初的想法是采用HashTable进行比对,不过大集合测试时超时了。一共有26个字符,所以可以用每一位表示一个字符是否出现,这样用int就足够表示一个字符串中出现的字符,采用按位操作就可以方便的比对两个字符串中是否有重复字符了。具体代码:

class Solution {
public:
    int maxProduct(vector<string>& words) {
        int rst = 0;
        int sz = words.size();
        vector<int> bit(sz, 0);
        for(int i=0; i<sz; ++i) {
            for(char ch:words[i]) bit[i] |= (1<<(ch-'a'));
        }
        for(int i=0; i<sz-1; ++i) {
            for(int j=i+1; j<sz; ++j) {
                if(bit[i]&bit[j]) continue;
                rst = max(rst, (int)(words[i].size()*words[j].size()));
            }
        }
        return rst;
    }
};
另外,查看别人代码时有人按字符串长度将数组进行排序,然后在比对过程中进行预先判断剪枝,效率上应该有所提高,感兴趣的同学可以自己实现。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值