您的位置:首页 > 职场人生

面试笔试杂项积累-leetcode 311-320

2016-02-15 22:30 483 查看

318.318-Reconstruct Itinerary-Difficulty: Medium

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.

方法一

思路

最长两个包含不同字母的string长度乘积

开始使用hashset判断是否有交集,但是超时,

public int MaxProduct(string[] words)
{
if (words.Length <= 1)
return 0;
HashSet<char>[] hash = new HashSet<char>[words.Length];
hash[0] = new HashSet<char>(words[0].ToCharArray());
int max = 0;
for (int i = 1; i < words.Length; i++)
{
hash[i] = new HashSet<char>(words[i].ToCharArray());
for (int j = i - 1; j > -1; j--)
{
HashSet<char> temp = new HashSet<char>(hash[i]);
temp.IntersectWith(hash[j]);
if (temp.Count <= 0)
max = Math.Max(max, words[i].Length * words[j].Length);
}
}
return max;
}

方法二

思路

使用位运算

把a-z每个字母都映射为二进制,然后存在一个int中,最后对每个string的二进制做&运算,如果&后为0则说明没有一个字母相同

public class Solution {
public int MaxProduct(string[] words) {
int[] checker = new int[words.Length];
int max = 0;
// populating the checker array with their respective numbers
for (int i = 0; i < checker.Length; i++)
{
int num = 0;
for (int j = 0; j < words[i].Length; j++)
{
num |= 1 << (words[i][j] - 'a');
}
checker[i] = num;
}

for (int i = 0; i < words.Length; i++)
{
for (int j = i + 1; j < words.Length; j++)
{
if ((checker[i] & checker[j]) == 0) //checking if the two strings have common character
max = Math.Max(max, words[i].Length * words[j].Length);
}
}
return max;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: