【发布时间】:2016-09-15 20:17:54
【问题描述】:
这是一道算法题:
给定一个字符串 s 和一个单词字典 dict,在 s 中添加空格 构造一个句子,其中每个单词都是有效的字典单词。
返回所有可能的句子。
例如,给定 s = "catsanddog", dict = ["cat", "cats", "and", “沙子”、“狗”]。
一个解决方案是["cats and dog", "cat sand dog"]。
解决方案如下,但我很难确定该解决方案的时间复杂度。谁能给我一些提示,特别是如果面试官在面试中问到这个时间复杂度,有没有一种不需要太多数学的快速方法来找到它?
public class Solution {
Map<String,List<String>> map = new HashMap();
public List<String> wordBreak(String s, Set<String> wordDict) {
List<String> res = new ArrayList<String>();
if(s == null || s.length() == 0) {
return res;
}
if(map.containsKey(s)) {
return map.get(s);
}
if(wordDict.contains(s)) {
res.add(s);
}
for(int i = 1 ; i < s.length() ; i++) {
String t = s.substring(i);
if(wordDict.contains(t)) {
List<String> temp = wordBreak(s.substring(0 , i) , wordDict);
if(temp.size() != 0) {
for(int j = 0 ; j < temp.size() ; j++) {
res.add(temp.get(j) + " " + t);
}
}
}
}
map.put(s , res);
return res;
}
}
【问题讨论】:
-
字典可以包含不是给定字符串s的子字符串的字符串吗?
-
@PEF 可以。
标签: java algorithm time-complexity big-o