每日一题 2019 - 05 - 07
题目:
Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words.
Note:
- The same word in the dictionary may be reused multiple times in the segmentation.
- You may assume the dictionary does not contain duplicate words.
Example 1:
1 | Input: s = "leetcode", wordDict = ["leet", "code"] |
Example 2:
1 | Input: s = "applepenapple", wordDict = ["apple", "pen"] |
Example 3:
1 | Input: s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"] |
解法:
这个题让根据给定的字典判断是否待定字符串可以分割为字典中的单词,刚开始拿到这个题的时候,我首先对词典进行遍历,通过消除字符串来判断是否能完成分割,但是发现在求解过程中会遇到问题,比如aaaaaa
,可以分割为 aaa
, aaa
,但是如果字典中同时给出 aaaa
与 aaa
,就没有办法完成任务了,所以只能换一种思路;
另外一种思路就是动态规划了,通过字符串找字典中的单词匹配情况, 从字符串从前往后匹配,如果当前位置可以与前面某位置结合得到一个单词(也即test[j-1] == true),那么证明当前位置可以在字典中完成匹配,重复这个过程,直到字符串结尾;
代码:
1 | class Solution { |