java - 使用字典中没有共同字母的成对单词,找到一对最大化单词长度总和的单词

标签 java string algorithm dictionary

问题:

Using pairs of words from a dictionary with no letters in common, find a pair that maximizes the sum of the words' lengths

Example Dictionary: mouse, cow, join, key, dog

dog and key share no letters and have a sum of 3+3 = 6

mouse does not work with cow, join, or dog because they all share the letter 'o'

join and key share no letters and have a sum of 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^2 * 26) 中执行此操作(26 代表字典中的字符数,可能是英文字母表)。

首先 构建一个二维 boolean 数组 D[i][j]。

i - 整数

j - 从'a'到'z'的字符(你可以用ASCII码代替字符)

如果索引 i 处的单词包含字母 j,则 D[i][j] = 1,否则 D[i][j] = 0;

在你有了这个二维数组之后,你可以检查每对单词是否有一个共同的字母(你迭代每一对,字典中的每个字母)。如果他们不这样做,您将实现最大金额。

关于java - 使用字典中没有共同字母的成对单词,找到一对最大化单词长度总和的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29734387/

相关文章:

algorithm - 我应该使用哪种优化算法来优化多层感知器的权重?

java - 使用 Lambda、Stream java 将值添加到两个嵌套的 JSON 数组中

java - 文件并行流

java - 有灵活的 Android 广告提供商吗?

java - 无法对非静态方法进行静态引用 - Android TabbedActivity

Python将长字符串转换为不带单引号的列表

python - 如何在 Python 中将 float 格式化为最大固定宽度

algorithm - 根据嵌套类型过滤对象列表

python - 如何在 Python 中删除反斜杠和附加在反斜杠上的单词?

objective-c - 我怎样才能在 Objective-C 中加速这个强力加法算法?