139. Word Break

每日一题 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
2
3
Input: s = "leetcode", wordDict = ["leet", "code"]
Output: true
Explanation: Return true because "leetcode" can be segmented as "leet code".

Example 2:

1
2
3
4
Input: s = "applepenapple", wordDict = ["apple", "pen"]
Output: true
Explanation: Return true because "applepenapple" can be segmented as "apple pen apple".
Note that you are allowed to reuse a dictionary word.

Example 3:

1
2
Input: s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"]
Output: false

解法:

这个题让根据给定的字典判断是否待定字符串可以分割为字典中的单词,刚开始拿到这个题的时候,我首先对词典进行遍历,通过消除字符串来判断是否能完成分割,但是发现在求解过程中会遇到问题,比如aaaaaa,可以分割为 aaa , aaa,但是如果字典中同时给出 aaaaaaa ,就没有办法完成任务了,所以只能换一种思路;

另外一种思路就是动态规划了,通过字符串找字典中的单词匹配情况, 从字符串从前往后匹配,如果当前位置可以与前面某位置结合得到一个单词(也即test[j-1] == true),那么证明当前位置可以在字典中完成匹配,重复这个过程,直到字符串结尾;


代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public:
bool wordBreak(string s, vector<string>& wordDict) {
vector<bool> test(s.size()+1,false);
test[0] = true ;
for(int i = 1 ; i <= s.size() ; i ++)
{
for(int j = i ; j > 0 ; j -- )
{
if(test[j-1] == false)
{
continue ;
}
if(find(wordDict.begin(),wordDict.end(),s.substr(j-1,i-j+1)) != wordDict.end())
{
test[i] = true ;
break ;
}
}
}
return test[s.size()];
}
};
0%
undefined