[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
原创粉丝点击