[LeetCode]318. Maximum Product of Word Lengths

来源:互联网 发布:vb能做到人脸识别吗 编辑:程序博客网 时间:2024/05/31 19:18

Problem Description

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.
[https://leetcode.com/problems/maximum-product-of-word-lengths/]

思路

用一个26位的数来表示一个字符串里出现过什么字母,例如1000…..0000
表示字符串中出现了’a’。这样marks[i]&marks[j]就可以表示i,j中有无出现相同的字符。
整体来说还是O(n^2)的。。。

Code

package q318;public class Solution {    public int maxProduct(String[] words) {        if(words.length<1) return 0;        int[] marks =new int[words.length];        char a;        for(int i=0;i<words.length;i++){            for(int j=0;j<words[i].length();j++){                a=words[i].charAt(j);                marks[i]=marks[i]|(1<<(a-'a'));            }        }        int max=0;        for(int i=0;i<words.length;i++){            for(int j=i;j<words.length;j++){                if((marks[i]&marks[j])!=0) continue;                else{                    max=Math.max(max, words[i].length()*words[j].length());                }            }        }        return max;    }//  public static void main(String[] args) {//      // TODO Auto-generated method stub////  }}
0 0
原创粉丝点击