一、题目来源
二、题目
给定一个字符串数组 words,请计算当两个字符串 words[i] 和 words[j] 不包含相同字符时,它们长度的乘积的最大值。假设字符串中只包含英语的小写字母。如果没有不包含相同字符的一对字符串,返回 0。
示例 1:
输入: words = ["abcw","baz","foo","bar","fxyz","abcdef"]
输出: 16
解释: 这两个单词为 "abcw", "fxyz"。它们不包含相同字符,且长度的乘积最大。
示例 2:
输入: words = ["a","ab","abc","d","cd","bcd","abcd"]
输出: 4
解释: 这两个单词为 "ab", "cd"。
输入: words = ["a","aa","aaa","aaaa"]
输出: 0
解释: 不存在这样的两个单词。
数据范围:
2 <= words.length <= 1000
1 <= words[i].length <= 1000
words[i] 仅包含小写字母
三、自己的思路
(1)遍历数组,用哈希表判断两个字符串是否有相同的字符
(2)再找出最大值,并返回
(2)时间复杂度是log(n*(n-1))
四、C++源码
class Solution {
int ans = 0;
int hash[26];
public:
bool judge(string a, string b) {
bool temp;
for(int i = 0; i < a.size(); ++i) {
hash[a[i]-'a']++;
}
for(int i = 0; i < b.size(); ++i) {
if(hash[b[i]-'a'] != 0){
temp = false;
break;
}else {
temp = true;
}
}
return temp;
}
int maxSquare(string a, string b) {
int temp = 0;
//printf("%s\t%s\n", a.c_str(), b.c_str());
if(judge(a, b))
temp = a.size() * b.size();
return temp;
}
int maxProduct(vector<string>& words) {
int i, j;
for(i = 0; i < words.size(); ++i) {
for(j = i+1; j < words.size(); ++j) {
memset(hash, 0, sizeof(hash));
ans = max(maxSquare(words[i], words[j]), ans);
}
}
return ans;
}
};
五、别人的思路
(1)状态压缩,把字母压缩成二进制
(2)然后通过与运算比较,如果结果为0的话,就说明没有相同字母
六、源码
class Solution {
public:
int maxProduct(vector<string>& words) {
int res = 0;
int n = words.size();
vector<int> wbit;
wbit.reserve(n);
for(string &s: words) {
int t = 0;
for(char& c:s) {
//abc->111
//def->111000
t |= 1 << (c -'a');
}
wbit.emplace_back(t);
}
for(int i = 1; i < n; ++i) {
for(int j = 0; j < i; ++j) {
if(wbit[i] & wbit[j]) continue;
res = max(res, int(words[i].size() * words[j].size()));
}
}
return res;
}
};
七、Java版本
class Solution {
public int maxProduct(String[] words) {
int len = words.length;
int[] nums = new int[len];
for(int i = 0; i < len; ++i) {
for(int j = 0; j < words[i].length(); ++j) {
nums[i] |= (1 << (words[i].charAt(j)-'a'));
}
}
int res = 0;
for(int i = 0; i < len-1; ++i) {
for(int j = i+1; j < len;++j) {
if((nums[i] & nums[j]) == 0) {
res = Math.max(res, words[i].length()*words[j].length());
}
}
}
return res;
}
}
八、总结
- printf不能直接输出string字符串的内容。printf函数输出字符串是针对char *的,即printf只能输出c语言的内置数据类型,而string不是c语言的内置数据类型。string类型的对象不止包含字符串,还包含了许多用于操作的函数,所以&str不是字符串的首地址。如果需要输出string对象中的字符串,可以使用string的成员函数c_str(),该函数返回字符串的首字符的地址。
- 复习位运算