赞
踩
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, return 0.
Input: words = [“abcw”,“baz”,“foo”,“bar”,“xtfn”,“abcdef”]
Output: 16
Explanation: The two words can be “abcw”, “xtfn”.
Input: words = [“a”,“ab”,“abc”,“d”,“cd”,“bcd”,“abcd”]
Output: 4
Explanation: The two words can be “ab”, “cd”.
Input: words = [“a”,“aa”,“aaa”,“aaaa”]
Output: 0
Explanation: No such pair of words.
From: LeetCode
Link: 318. Maximum Product of Word Lengths
1. hasCommonLetters Function:
2. maxProduct Function:
3. Efficiency:
// Function to check if two words share common letters int hasCommonLetters(const char* word1, const char* word2) { int letters1 = 0, letters2 = 0; // Mark presence of each character in the first word while (*word1) { letters1 |= 1 << (*word1 - 'a'); word1++; } // Mark presence of each character in the second word while (*word2) { letters2 |= 1 << (*word2 - 'a'); word2++; } // If there is any common letter, the AND of the two will be non-zero return letters1 & letters2; } int maxProduct(char** words, int wordsSize) { int maxProduct = 0; // Iterate through all pairs of words for (int i = 0; i < wordsSize; i++) { for (int j = i + 1; j < wordsSize; j++) { // Check if words[i] and words[j] share common letters if (!hasCommonLetters(words[i], words[j])) { int product = strlen(words[i]) * strlen(words[j]); if (product > maxProduct) { maxProduct = product; } } } } return maxProduct; }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。