318. Maximum Product of Word Lengths
来源:互联网 发布:淘宝全球购为什么便宜 编辑:程序博客网 时间:2024/05/19 09:38
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.
思路:本题最直观的想法肯定是一个字符串一个字符串的比较,但是自己心里肯定也清楚,肯定是TLE的。我们可以优化比较两个字符串是否有公共部分的方法,用一个bitmap[i]表示words[i]转化后的2进制值,比如abc对应的是111,如果两个words[i]一位都不一样的话,想与就为0,。根据上面的思路可以得到ac的代码。
代码如下(已通过leetcode)
public class Solution {
public int maxProduct(String[] words) {
int[] map=new int[words.length];
//Arrays.fill(map, 1);
for(int i=0;i<words.length;i++) {
for(int j=0;j<words[i].length();j++) {
map[i]=map[i]|(1<<words[i].charAt(j)-'a');
}
}
int max=0;
for(int i=words.length-1;i>=1;i--) {
for(int j=i-1;j>=0;j--) {
if((map[i]&map[j])==0) {
max=Math.max(max, words[i].length()*words[j].length());
}
}
}
return max;
}
}
- 【leetcode】318. Maximum Product of Word Lengths
- 318. Maximum Product of Word Lengths LeetCode
- [leetcode] 318. Maximum Product of Word Lengths
- 318. Maximum Product of Word Lengths
- LeetCode: 318. Maximum Product of Word Lengths
- LeetCode 318. Maximum Product of Word Lengths
- leetcode 318. Maximum Product of Word Lengths
- 318. Maximum Product of Word Lengths
- [LeetCode]318. Maximum Product of Word Lengths
- [LeetCode]318. Maximum Product of Word Lengths
- 318. Maximum Product of Word Lengths
- 318. Maximum Product of Word Lengths
- 318. Maximum Product of Word Lengths
- LeetCode 318. Maximum Product of Word Lengths
- 318. Maximum Product of Word Lengths
- 318. Maximum Product of Word Lengths
- LeetCode *** 318. Maximum Product of Word Lengths
- 318. Maximum Product of Word Lengths
- delphi socket客户端连接服务端时的错误
- PHP PDO ACCESS 留言板-数据库设计
- 动态规划之0-1背包问题
- python 新手入门学习(一)
- 卸载Visual Studio Professional 2013
- 318. Maximum Product of Word Lengths
- RecyclerView 的使用(1)
- kubernetes中执行kubectl报错:kubectl: command not found
- 【Makefile学习笔记】报错提示
- 如何从outlook ost恢复数据(ost导入outlook)
- 运算符重载之转换运算符
- MySQL主从复制
- opencv 人脸识别 (一)训练样本的处理
- 2345手机助手类似于百度的WormHole漏洞