从字典条目创建给定的字符串

问题描述 投票:6回答:3

在最近的一次面试中,我被要求解决以下问题:

给定一个字符串s(没有空格)和一个字典,返回组成字符串的字典中的单词。

例如,s= peachpie, dic= {peach, pie}, result={peach, pie}

我会问这个问题的决定变化:

如果s可以在字典中组成单词返回yes,否则返回no

我的解决方案是回溯(用Java编写)

public static boolean words(String s, Set<String> dictionary)
{
    if ("".equals(s))
        return true;

    for (int i=0; i <= s.length(); i++)
    {
        String pre = prefix(s,i); // returns s[0..i-1]
        String suf = suffix(s,i); // returns s[i..s.len]
        if (dictionary.contains(pre) && words(suf, dictionary))
            return true;
    }
    return false;
}

public static void main(String[] args) {
    Set<String> dic = new HashSet<String>();
    dic.add("peach");
    dic.add("pie");
    dic.add("1");

    System.out.println(words("peachpie1", dic)); // true
    System.out.println(words("peachpie2", dic)); // false
}

这个解决方案的时间复杂度是多少?我在for循环中递归调用,但仅限于字典中的前缀。

有任何想法吗?

algorithm complexity-theory backtracking
3个回答
5
投票

您可以轻松创建一个程序至少需要指数时间才能完成的情况。我们只需要一个词aaa...aaab,其中a重复n次。字典只包含两个单词,aaa

b最终确保函数永远不会找到匹配因此永远不会过早退出。

在每个words执行时,将产生两个递归调用:使用suffix(s, 1)suffix(s, 2)。因此,执行时间像斐波那契数字一样增长:t(n) = t(n - 1) + t(n - 2)。 (您可以通过插入计数器来验证它。)因此,复杂性肯定不是多项式的。 (这甚至不是最糟糕的输入)

但您可以使用Memoization轻松改善您的解决方案。请注意,函数words的输出仅取决于一件事:我们在原始字符串中的哪个位置开始。例如,如果我们有一个字符串abcdefgwords(5)被调用,那么abcde究竟是如何组成的(如ab+c+dea+b+c+d+e或其他东西)并不重要。因此,我们不必每次都重新计算words("fg")。 在原始版本中,这可以这样做

public static boolean words(String s, Set<String> dictionary) {
    if (processed.contains(s)) {
        // we've already processed string 's' with no luck
        return false;
    }

    // your normal computations
    // ...

    // if no match found, add 's' to the list of checked inputs
    processed.add(s);
    return false;
}

PS仍然,我鼓励你将words(String)改为words(int)。这样,您就可以将结果存储在数组中,甚至可以将整个算法转换为DP(这会使其更加简单)。

编辑2 由于我除了工作之外没什么可做的,这里是DP(动态编程)解决方案。与上面的想法相同。

    String s = "peachpie1";
    int n = s.length();
    boolean[] a = new boolean[n + 1];
    // a[i] tells whether s[i..n-1] can be composed from words in the dictionary
    a[n] = true; // always can compose empty string

    for (int start = n - 1; start >= 0; --start) {
        for (String word : dictionary) {
            if (start + word.length() <= n && a[start + word.length()]) {
                // check if 'word' is a prefix of s[start..n-1]
                String test = s.substring(start, start + word.length());
                if (test.equals(word)) {
                    a[start] = true;
                    break;
                }
            }
        }
    }

    System.out.println(a[0]);

1
投票

这是一个动态编程解决方案,它计算将字符串分解为单词的总方式。它解决了您的原始问题,因为如果分解的数量为正,则字符串是可分解的。

def count_decompositions(dictionary, word):
    n = len(word)
    results = [1] + [0] * n
    for i in xrange(1, n + 1):
        for j in xrange(i):
            if word[n - i:n - j] in dictionary:
                results[i] += results[j]
    return results[n]

存储O(n),运行时间O(n ^ 2)。


0
投票

所有字符串上的循环将采用n。找到所有后缀和前缀将需要n + (n - 1) + (n - 2) + .... + 1n第一次调用words(n - 1)获得第二次等等),这是

n^2 - SUM(1..n) = n^2 - (n^2 + n)/2 = n^2 / 2 - n / 2

在复杂性理论中它相当于n ^ 2。

在正常情况下检查HashSet中是否存在是Theta(1),但在最坏的情况下它是O(n)。

因此,算法的正常情况复杂度为Theta(n ^ 2),最差情况为O(n ^ 3)。

编辑:我混淆了递归和迭代的顺序,所以这个答案是错误的。实际上,时间依赖于n指数(例如,与斐波纳契数的计算相比)。

更有趣的是如何改进算法的问题。传统上用于字符串操作suffix tree。您可以使用字符串构建后缀树,并在算法开始时将所有节点标记为“未跟踪”。然后遍历集合中的字符串,每次使用某个节点时,将其标记为“已跟踪”。如果在树中找到集合中的所有字符串,则表示原始字符串包含set中的所有子字符串。如果所有节点都标记为已跟踪,则表示该字符串仅包含来自set的子字符串。

这种方法的实际复杂性取决于许多因素,如树构建算法,但至少它允许将问题分成几个独立的子任务,因此通过最昂贵的子任务的复杂性来衡量最终的复杂性。

© www.soinside.com 2019 - 2024. All rights reserved.