【发布时间】:2015-06-26 09:09:42
【问题描述】:
问题:
使用字典中没有共同字母的单词对,找到 最大化单词长度总和的一对
示例字典:mouse、cow、join、key、dog
dog 和 key 不共用字母,总和为 3+3 = 6
mouse 不适用于 cow、join 或 dog,因为它们都共享字母 'o '
join 和 key 不共用字母,总和为 4+3 = 7
我在一次采访中遇到了这个问题,我想出的解决方案概述如下。我想知道是否有任何方法可以提高效率?我使用了两个BitSets 来映射两个单词的字母表,并将它们组合在一起以查看它们是否包含相同的字母。我认为我的算法的复杂度为 o(n!),效率低下,有没有更好的方法来优化我的算法?
public static void maximumSum (String[] dictionary) {
// ascii of a = 97
BitSet word1 = new BitSet(26);
BitSet word2 = new BitSet(26);
String maxWord1 = "";
String maxWord2 = "";
int maxSum = -1;
for(int i = 0; i<dictionary.length; i++) {
for(int j = i+1; j<dictionary.length; j++) {
String s1 = dictionary[i];
String s2 = dictionary[j];
for(int k = 0; k<s1.length(); k++) {
word1.set(s1.charAt(k)-97);
}
for(int k = 0; k<s2.length(); k++) {
word2.set(s2.charAt(k)-97);
}
word1.and(word2);
if(word1.cardinality() == 0) {
if(maxSum < s1.length()+s2.length()) {
maxWord1 = s1;
maxWord2 = s2;
maxSum = s1.length()+s2.length();
}
}
word1.clear();
word2.clear();
}
}
if(maxSum == -1)
System.out.println("All the words have letters in common.");
else
System.out.println("'"+maxWord1+"' and '"+maxWord2+"'
have a maximum sum of "+maxSum);
}
public static void main(String[] args) {
String[] dictionary = {"mouse", "cow", "join", "key", "dog"};
maximumSum(dictionary);
}
输出:
'join' and 'key' have a maximum sum of 7
【问题讨论】:
-
我不知道你为什么说 o(n!)。您的算法对于蛮力方法有点低效,但它是 O(n^2 avg(length)) 其中 avg(length) 表示字典中单词的平均长度。正如 Bogdan Pop 回答的那样,通过只计算每个单词的内容一次,您可以非常轻松地提高效率。应该有比蛮力更好的方法,但是 n^2 比 n! 好很多。
-
Quora 上有同样的问题:quora.com/…
-
谢谢!我不太确定复杂性,感谢您澄清这一点。
-
Hmmmmm,如果一个字母可能在一个单词中重复 - 它会改变最佳方法:
join和keyyyyyyyy不共享字母,但长度大于join和key.
标签: java string algorithm dictionary