Maximum Product of Word Lengths 问题及解法
来源:互联网 发布:淘宝卖家子账号 编辑:程序博客网 时间:2024/06/09 15:32
问题描述:
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.
示例:
Given ["abcw", "baz", "foo", "bar", "xtfn", "abcdef"]
Return 16
The two words can be "abcw", "xtfn"
.
Given ["a", "ab", "abc", "d", "cd", "bcd", "abcd"]
Return 4
The two words can be "ab", "cd"
.
Given ["a", "aa", "aaa", "aaaa"]
Return 0
No such pair of words.
问题分析:
将每个字串中的字母都映射到二进制位上,所有出现相同字母的字串,他们对应的二进制数按位与所得的值均不为0,利用这个性质即可求解问题。
过程详见代码:
class Solution {public: int maxProduct(vector<string>& words) { int res = 0;vector<int> byte(words.size());for (int i = 0; i < words.size(); i++){int val = 0;for (int j = 0; j < words[i].size(); j++){val |= (1 << (words[i][j] - 'a'));}byte[i] = val; }for (int i = 0; i < words.size(); i++){for (int j = i + 1; j < words.size(); j++){if ((byte[i] & byte[j]) == 0){res = max(res, (int)(words[i].length() * words[j].length()));}}}return res; }};
阅读全文
0 0
- Maximum Product of Word Lengths 问题及解法
- 318 Maximum Product of Word Lengths解法解析
- Maximum Product of Word Lengths
- Maximum Product of Word Lengths
- Maximum Product of Word Lengths
- Maximum Product of Word Lengths
- Maximum Product of Word Lengths
- Maximum Product of Word Lengths
- Maximum Product of Word Lengths
- Maximum Product of Word Lengths
- Maximum Product of Word Lengths
- Maximum Product of Word Lengths
- Maximum Product of Word Lengths
- Maximum Product of Word Lengths
- Maximum Product of Word Lengths
- Maximum Product of Word Lengths
- 【Leetcode】:318. Maximum Product of Word Lengths 问题 in JAVA
- leetcode Maximum Product of Word Lengths
- hive开发遇到的一些坑
- 【拜小白opencv】31-平滑处理4非线性滤波之——中值滤波
- 昨天的一些代码笔记
- ssh链接Ubuntu出现REMOTE HOST IDENTIFICATION HAS CHANGED的问题
- Java 之中文转拼音
- Maximum Product of Word Lengths 问题及解法
- Redis数据库安装(Linux)
- oracle时间获取记录
- Ubuntu 装机必备设置与软件安装
- MyBatis中resultType和resultMap的区别
- 《机器学习实战》代码片段学习6 k均值聚类与二分k均值聚类
- js的学习(1)
- 本地存储-webStorage
- mysql中按中文名称排序时的问题