leecode 解题总结:318. Maximum Product of Word Lengths

#include <iostream>
#include <stdio.h>
#include <vector>
#include <string>
#include <unordered_set>
using namespace std;
/*
问题:
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".

Example 2:
Given ["a", "ab", "abc", "d", "cd", "bcd", "abcd"]
Return 4
The two words can be "ab", "cd".

Example 3:
Given ["a", "aa", "aaa", "aaaa"]
Return 0
No such pair of words.

分析:本题实际上是求不包含相同字母的两个字符串长度的最大乘积
最简单的方法:采用一个二层循环,对于当前遍历的字符串,计算剩余所有字符串
与其不包含相同字母条件下的两字符串长度的最大乘积。时间复杂度为O(k*n^2),n
为字符串的个数,k为字符串平均长度。
如何判断两个字符串不包含相同的字母:采用一个哈希set,首先遍历第一个字符串,将
所有字符插入set,,然后遍历第二个字符串的每个字符,看该字符如果在哈希set中
已经出现,则直接返回不符合

特殊情况:如果字符串列表中只有一个字符,应该返回0;

输入:
6(字符串个数)
abcw baz foo bar xtfn abcdef
7
a ab abc d cd bcd abcd
4
a aa aaa aaaa
输出:
16
4
0


果然超时。O(k*n^2)的方法超时,

关键:
1 参考leecode解法:https://discuss.leetcode.com/topic/35539/java-easy-version-to-understand
由于只有26个字符,采用位运算,从右往左第25位到从右往左起第0位到分别代表:
zyx...cba
只需要计算两个字符串转化为的整数值相与如果为0,表示无重复字母。牛逼,
限定了字符<=32位和最大值的范围,通过位图解决
*/

class Solution {
public:

    int maxProduct(vector<string>& words) {
		if(words.empty() || 1 == words.size())
		{
			return 0;
		}
		int size = words.size();
		int maxProduct = 0;
		vector<int> values(size , 0);
		//将每个字符串转化为整型值
		for(int i = 0 ; i < size ; i++)
		{
			int len = words.at(i).length();
			for(int j = 0 ; j < len ; j++)
			{
				//按照zyx...cba的形式摆放
				values[i] |= (1 << (words.at(i).at(j) - 'a'));
			}
		}
		
		//通过判断字符串转化的整形数进行与操作如果为0,表示无相同字符
		for(int i = 0 ; i < size - 1 ; i++)
		{
			for(int j = i + 1 ; j < size; j++)
			{
				if(0 == (values.at(i) & values.at(j)) && ( words.at(i).length() * words.at(j).length() > maxProduct ))
				{
					maxProduct = words.at(i).length() * words.at(j).length();
				}
			}
		}
		return maxProduct;
    }
};


void process()
{
	 vector<string> words;
	 string value;
	 int num;
	 Solution solution;
	 while(cin >> num )
	 {
		 words.clear();
		 for(int i = 0 ; i < num ; i++)
		 {
			 cin >> value;
			 words.push_back(value);
		 }
		 int result = solution.maxProduct(words);
		 cout << result << endl;
	 }
}

int main(int argc , char* argv[])
{
	process();
	getchar();
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值