318. Maximum Product of Word Lengths
2016-06-30 05:09
302 查看
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.
这个问题我们第一反应,应该是使用 set 或者 map 来确认每个词之间没有重复的字母,可以想到,这个方法无疑是很慢的,考虑到每个字符都要做一次比较,其复杂度比 n^2更多。
这道题目同时也给了我们一个很好的提示:字符问题可以用 bit manipulate 来解决的。
因为 int 总共32位,所以完全可以容纳26个字符。我们将比较字符串变成了比较整数。
public class Solution { public int maxProduct(String[] words) { if(words == null || words.length == 0){ return 0; } int dist = Integer.MIN_VALUE; int[] bit = new int[words.length]; for(int i = 0; i < words.length; i++){ for(int j = 0; j<words[i].length(); j++){ bit[i] |= 1<<(words[i].charAt(j) -'a'); } } for(int i = 0; i< words.length -1; i++){ for(int j = i + 1; j<words.length;j++){ if((bit[i] & bit[j]) == 0 ){ dist = Math.max(words[i].length() * words[j].length(),dist); } } } return dist == Integer.MIN_VALUE? 0:dist; } }
相关文章推荐
- Android之获取手机上的图片和视频缩略图thumbnails
- android string.xml文件中的整型和string型代替
- Android java 与 javascript互访(相互调用)的方法例子
- android上改变listView的选中颜色
- String.intern
- Prototype源码浅析 String部分(二)
- Ruby中的String对象学习笔记
- 微软Word 2007数学插件 Microsoft Math 提供下载
- Office Word九条常用技巧
- PostgreSQL ERROR: invalid escape string 解决办法
- C#实现简单合并word文档的方法
- powershell操作word详解
- C#生成Word文档代码示例
- 用vbscript把 Word 文档保存为文本文件的代码
- 如何使用C#从word文档中提取图片
- C#根据Word模版生成Word文件
- C#采用OpenXml给Word文档添加表格
- C#实现合并多个word文档的方法
- C#采用OpenXml给word里面插入图片
- C#实现DataSet内数据转化为Excel和Word文件的通用类完整实例