【问题标题】:Getting all combination of array elements that form a given string获取构成给定字符串的数组元素的所有组合
【发布时间】:2015-03-18 18:34:19
【问题描述】:

我被这个面试问题困住了。 给定一个单词 S 和一个字符串数组 A。如何找到可以形成 S 的 A 元素的所有可能组合。 示例:

S = "hotday"
A = ["o","ho","h","tday"]

可能的组合是:("h"+"o"+"tday") 和 ("ho"+"tday")。

谢谢

【问题讨论】:

    标签: algorithm recursion


    【解决方案1】:

    您可以使用回溯。这是一些伪代码:

    def generateSolutions(unusedWords, usedWords, string, position):
        if position == string.length():
            print(usedWords)
        else:
             for word in unusedWords:
                 if word is a prefix of string[position ... s.length() - 1]:
                     generateSolutions(unusedWords - word, usedWords + word, 
                                       string, position + word.length())
    
    generateSolution(words, an empty list, input string, 0)
    

    这个想法很简单:我们可以只选择一个与输入字符串其余部分的前缀匹配的未使用的单词,并继续递归生成所有有效的组合(我假设我们只能使用给定单词列表中的每个单词一次)。该解决方案具有指数时间复杂度,但在最坏的情况下不可能做得更好。例如,如果给定字符串为abcdef...yz,单词列表为[a, b, c, ..., z, ab, cd, ..., yz],则此类组合的数量为2 ^ n / 2,其中n是给定字符串的长度。

    【讨论】:

    • 拥有 A 的元素的 prefix tree 可能会很好。然后您可以更快地识别作为字符串前缀的单词。
    • @Kevin : 如何在这个解决方案中集成前缀树?
    • @user199 当我们需要查找一个单词是否是string[position...]的前缀时,我们可以遍历前缀树而不是遍历所有单词。
    • @ILoveCoding :我在 java 中实现了您的解决方案(参见下面的代码),它工作正常。但是你不觉得没有必要使用 Tries 吗?我只是用了一种方法; getPrefixes(S,pos) 生成一组可能的前缀。我看不出 Trie 如何改善这一点。你能解释一下吗?
    • @user199 trie 可以提高其性能。如果没有性能问题,则无需尝试。
    【解决方案2】:

    您可以遍历 A 的所有排列并查看适合的排列。 Python 示例实现:

    import itertools
    S = "hotday"
    A = ["o","ho","h","tday"]
    for count in range(len(A)):
        for pieces in itertools.permutations(A, count):
            if "".join(pieces) == S:
                print pieces
    

    结果:

    ('ho', 'tday')
    ('h', 'o', 'tday')
    

    是的,这是 O(N!),但这对于您提供的小 A 来说没问题。

    【讨论】:

    • 我不会否认这一点。但是慢速算法总比没有算法好;-)
    【解决方案3】:

    这是我的java解决方案,是“ILoveCoding”伪代码的实现:

    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.HashSet;
    
    
    public class PossibleCombination {
    
    
        public static void printPossibleCombinations(String[] tab, String S)
        {
            ArrayList<String> used = new ArrayList<String>();
            ArrayList<String> notused = new ArrayList<String>(Arrays.asList(tab));
            printPossibleCombinations(used, notused, S,0);
        }
    
        private static void printPossibleCombinations(ArrayList<String> used,
                ArrayList<String> notused, String s,int pos) {
                if (pos == s.length())
                {                   System.out.println("Possible combinaiton : ");
    
                    for(String e : used)
                    {
                        System.out.print(e + " - ");
                        System.out.println();
                    }
                }
                HashSet<String> prefixes = getPossiblePrefixes(s,pos);
                for(String e : notused)
                {
    
                    if (prefixes.contains(e))
                    {
                        ArrayList<String> isused = new ArrayList<String>(used);
                        isused.add(e);
                        ArrayList<String> isnotused = new ArrayList<String>(notused);
                        isnotused.remove(e);
                        printPossibleCombinations(isused, isnotused,s, pos + e.length());
                    }
                }
    
        }
    
        private static HashSet<String> getPossiblePrefixes(String s, int pos) {
            HashSet<String> prefixes = new HashSet<String>();
            for(int i = pos ; i<= s.length() ; i++)
            {
                prefixes.add(s.substring(pos,i));
            }
            return prefixes;
        }
    
        public static void main(String[] args) {
    
            String[] tab = {"o","ho","h","tday"};
            String S = "hotday";
            printPossibleCombinations(tab, S);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2017-10-28
      • 2014-12-17
      • 2017-07-20
      • 1970-01-01
      • 2012-08-16
      • 1970-01-01
      • 2017-10-11
      • 1970-01-01
      相关资源
      最近更新 更多