【Leetcode】318. Maximum Product of Word Lengths
来源:互联网 发布:朔州seo搜索优化 编辑:程序博客网 时间:2024/05/21 10:17
方法一:(空间复杂度O(1),时间复杂度O(n^2))
很简单的多次遍历的方式:
public int maxProduct(String[] words) {
int res = 0;
boolean flag;
for(int i=0;i<words.length;i++){
for(int j=i+1;j<words.length;j++){
if(words[i].length()*words[j].length() > res){
flag =false;
for(int k=0;k<words[i].length();k++){
if(words[j].indexOf(words[i].charAt(k)) != -1){
flag = true;
break;
}
}
if(!flag){
res = words[i].length()*words[j].length();
}
}
}
}
return res;
}
运行结果:
方法二(空间复杂度O(n),时间复杂度O(n^2))
觉得方法一的运行速度过慢,增加了一点空间复杂度,在工程上优化了一下。创建一个数组,用int的比特位存每个字符串单词的出现情况。之后检测两个字符串有没有相同的单词只需要对两个整数做交就行了。嗯,在速度上确实提升挺多。
public int maxProduct(String[] words) {
int res = 0;
int[] wordsArray = new int[words.length];
for(int i=0;i<words.length;i++){
for(int k=0;k<words[i].length();k++){
wordsArray[i] = wordsArray[i]|1<<(words[i].charAt(k)-97);
}
}
for(int i=0;i<words.length;i++){
for(int j=i+1;j<words.length;j++){
if(words[i].length()*words[j].length() > res){
if((wordsArray[i]&wordsArray[j])==0){
res = words[i].length()*words[j].length();
}
}
}
}
return res;
}
'''
我还没想出更好的算法,先留坑吧
'''
- 【leetcode】318. Maximum Product of Word Lengths
- 318. Maximum Product of Word Lengths LeetCode
- [leetcode] 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
- [LeetCode]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
- [Leetcode] 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
- [LEETCODE]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
- 以太网协议以及常用帧格式
- 【NOIP2016提高组复赛】玩具谜题
- 搜索入门(DFS)最简单的部分和问题
- poj_1850 Code(组合数学/dfs)
- 11月28日 课堂笔记
- 【Leetcode】318. Maximum Product of Word Lengths
- 阅读资料
- 属性动画05-ObjectAnimator的高级使用
- 常见对象_把字符串中的数字排序案例
- 基于maven配置jetty运行
- TMS320F28335/ <2> CCS5.5调试过程如何查看GPIO端口的状态
- 半结构化、结构化以及非结构化数据
- 链表
- Nsight Monitor无法正常打开