318 Maximum Product of Word Lengths解法解析

来源:互联网 发布:广数980锥度螺纹编程 编辑:程序博客网 时间:2024/05/29 04:05

题目为:

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.

主要有两个思路:

1.最直接的思路,利用两层遍历后找到每个单词,接着对每个单词进行比较是否存在相同字母。时间复杂度为O(n^4)。

代码如下:

public class Solution {
    public int maxProduct(String[] words) {
         //耗时的做法
int max=0;
       for(int i=0;i<words.length;i++){
       
        for(int j=i;j<words.length;j++){
        String cur=words[i];
        String mani=words[j];
       
        HashMap<Character,Integer> curMap= new HashMap();
        for(int k=0;k<cur.length();k++){
        if(curMap.containsKey(cur.charAt(k)))
        curMap.put(cur.charAt(k), curMap.get(cur.charAt(k))+1);
        else  curMap.put(cur.charAt(k), 1);
        }
        int flag=0;
        for(int l=0;l<mani.length();l++){
        if(!curMap.containsKey(mani.charAt(l)))
        flag++;
        }
        if((flag==mani.length())&&max<=cur.length()*mani.length())
        max=cur.length()*mani.length();
       
        }
       }
       return max;
    }
}

2.利用位操作,利用两层遍历,分两个步骤:

1)定义一个字母位数组,长度为单词个数,对26位的字母位分别赋值,字母存在则为1,字母不存在则为0。

2)两层遍历字符串数组,相与不同单词的字母位数组,结果为0则表示不存在相同的字母,结果为1则存在。

public class Solution {
    public int maxProduct(String[] words) {
        //利用按照位与的操作
int maniBit[]=new int[words.length];
for(int i=0;i<words.length;i++){
maniBit[i]=0;
String cur=words[i];
for(int j=0;j<cur.length();j++){
//相当于每一个数组里面保存了一个26位的一个整数,
//其中每一位代表的是每一个单词,出现则为1不出现则为0
maniBit[i]=maniBit[i]|(1<<cur.charAt(j)-'a');

}
int max=0;
for(int i=0;i<words.length;i++){
for(int j=i+1;j<words.length;j++){
if((maniBit[i]&maniBit[j])==0&&max<=words[i].length()*words[j].length())
max=words[i].length()*words[j].length();
}
}
return max;
    }
}

0 0
原创粉丝点击