问题描述

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".

思路

将 string 转化为 int,通过按位与来判断两个 string 是否含有相同的字母

提交

    public class Solution {
    
        public int maxProduct(String[] words) {
            int size = words.length;
            int[] nums = new int[size];
            for (int i = 0; i < size; i++) {
                nums[i] = wordToNum(words[i]);
            }
    
            int max = Integer.MIN_VALUE;
            for (int i = 0; i < size; i++) {
                for (int j = i + 1; j < size; j++) {
                    if ((nums[i] & nums[j]) == 0) {
                        max = Math.max(max, words[i].length() * words[j].length());
                    }
                }
            }
            return max == Integer.MIN_VALUE ? 0 : max;
        }
    
        public int wordToNum(String string) {
            int result = 0;
            int size = string.length();
            for (int i = 0; i < size; i++) {
                result |= 1 << (string.charAt(i) - 'a');
            }
            return result;
        }
    }

xingpingz
122 声望64 粉丝

博学,审问,慎思,明辨,力行


引用和评论

0 条评论