面试笔试杂项积累-leetcode 311-320
2016-02-15 22:30
483 查看
318.318-Reconstruct Itinerary-Difficulty: Medium
Given a string arraywords, 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;
}
}
相关文章推荐
- 一位极客美女打造了一款能为她做“口活”的装置
- leetcode - Super Ugly Number
- 面试经验
- 曝各城市娶妻成本:深圳208万 程序员成为“妻奴”?
- 一道常被人轻视的前端JS面试题(转)
- 面试题:旋转数组的最小数字
- 位运算及相关面试题汇总
- 程序员,你的安全感呢?
- To Java程序员:切勿用普通for循环遍历LinkedList(转)
- android面试题目2
- JAVA面试题大全整理
- 整理JAVA面试题
- IT企业面试题(java描述)-字符串旋转(旋转字母或者单词)
- 那些程序员的搞笑牛逼注释
- 埃米尼亚.伊瓦拉:如何转变职业生涯?
- 海量数据处理面试题
- 软件开发者的职业发展之路
- 一道常被人轻视的web前端常见面试题(JS)
- iOS面试题六
- 记录自己的码农进军之路