[LeetCode]318. Maximum Product of Word Lengths
来源:互联网 发布:胡公子淘宝店铺 编辑:程序博客网 时间:2024/05/23 19:16
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.
解题思路:用一个变量max暂存当前单词长度乘积的最大结果,当比较两个单词时,先判断两个单词长度的成绩是否大于max,若大于,则判断两个单词是否含有相同字母,若没有,则更新max,直到检索全部单词对。
public int maxProduct(String[] words) {if (words.length == 0) return 0;int max = 0;int l1 = 0;int l2 = 0;for (int i = 0;i < words.length;i++) {for (int j = i+1; j < words.length;j++) { l1 = words[i].length(); l2 = words[j].length();if (max < l1 * l2){if(!hasSameChar(words[i],words[j])) max = l1 * l2 ;}}}return max;}public boolean hasSameChar(String a,String b) {int[] s = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};int[] t = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};for(int i = 0; i < a.length();i++) {s[a.charAt(i)-97] = 1;}for(int i = 0; i < b.length();i++) {t[b.charAt(i)-97] = 1;}for(int i = 0; i < s.length;i++){if(s[i] == 1 && t[i] == 1) {return true; }}return false;}
0 0
- 【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
- [LeetCode]94. Binary Tree Inorder Traversal
- android页面滑动时,顶部title背景渐变的实现
- error C4996: 'GetVersionExW': 被声明为已否决
- English-The Best Time of My Life
- [FAQ10908][Message]开启固定拨号FDN功能(无法发短信的原因),发送信息时如何做FDN check
- [LeetCode]318. Maximum Product of Word Lengths
- 【WebService】第二章、XML文件命名空间以及约束
- java 安装及配置
- hdu1372 Knight Moves(马步bfs水)
- python中的cm()len() list() and tuple()以及一些内建函数
- HDU 5063Operation the Sequence(暴力)
- 致敬阿里云
- Plus One
- SQL读书笔记(六) 子查询