leetcode140.Word Break II
题目要求
1 | Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, add spaces in s to construct a sentence where each word is a valid dictionary word. You may assume the dictionary does not contain duplicate words. |
现在有一个非空字符串s和一个非空的字典wordDict。现在向s中添加空格从而构成一个句子,其中这个句子的所有单词都存在与wordDic中。字典中不包含重复的单词。
思路和代码
我们只需要每次从当前字符串中进行一次分割,该分割保证前一部分为字典中的一个单词,然后我们将后一部分作为子字符串递归的传入方法获取子字符串的分割。
catsanddog
cat | sanddog
cat | sand | dog
cats | anddog
cats | and | dog
但是单纯的递归会带来超时的情况,尤其是当字典中的单词出现大量包含的情况,如:[a,aa,aaa,aaaa],而输入为aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
我们可以利用HashMap缓存来解决这个问题,其中key为子字符串,value为其分割的结果的列表。
1 | private Map<String, List<String>> cache = new HashMap<String, List<String>>(); |