【发布时间】:2019-03-16 20:44:45
【问题描述】:
在最近的一次求职面试中,我被要求给出一个解决以下问题的方法:
给定一个字符串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 循环中递归调用,但只针对字典中的前缀。
有什么想法吗?
【问题讨论】:
-
单词是否只需要由字典中的单词组成?例如,如果 apple 不在字典中,applepie 的结果是什么?
-
@Gumbo 查看他的示例,最后一行包含一些但不是所有单词(缺少#2),因此字典必须包含所有单词。允许复读吗?例如,给定示例中的字典,“peachpeach”应该是真还是假?
-
@Mackey Repitition 没有定义,但我假设它是允许的
-
@Gumbo,
applepie的结果显然是错误的。看问题的定义:如果s可以由字典中的单词组成,则返回yes。apple不在字典中 -
@Matt 之所以有效,是因为我在后缀上递归调用
words。
标签: algorithm complexity-theory backtracking