318. Maximum Product of Word Lengths

1. Question

Given a string array words, return the maximum value of `length(word[i]) length(word[j])where the two words do not share common letters.* If no such two words exist, return0`.

2. Examples

Example 1:

Input: words = ["abcw","baz","foo","bar","xtfn","abcdef"]
Output: 16
Explanation: The two words can be "abcw", "xtfn".

Example 2:

Input: words = ["a","ab","abc","d","cd","bcd","abcd"]
Output: 4
Explanation: The two words can be "ab", "cd".

Example 3:

Input: words = ["a","aa","aaa","aaaa"]
Output: 0
Explanation: No such pair of words.

3. Constraints

  • 2 <= words.length <= 1000
  • 1 <= words[i].length <= 1000
  • words[i] consists only of lowercase English letters.

4. References

来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/maximum-product-of-word-lengths 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

5. Solutions

class Solution {
  public int maxProduct(String[] words) {
    int len = words.length;
    int[] arr = new int[len];

    for (int i = 0; i < len; i++) {
      char[] ch = words[i].toCharArray();

      for (char c : ch) {
        // 此处是一个异或运算,用二进制标志是否已经有此字母。
        // c - 'a' 计算出要位移的个数,将1进行左移,并与对应的int值进行或运算。
        // ac --> 00000...00101
        arr[i] |= 1 << (c - 'a');
      }
    }

    int res = 0;
    for (int i = 0; i < len; i++) {
      for (int j = i + 1; j < len; j++) {
        // 与运算
        if ((arr[i] & arr[j]) == 0) {
          res = Math.max(res, words[i].length() * words[j].length());
        }
      }
    }
    return res;
  }
}
Copyright © rootwhois.cn 2021-2022 all right reserved,powered by GitbookFile Modify: 2022-11-26 20:03:31

results matching ""

    No results matching ""