题目:
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:
Input: s = “leetcode”, wordDict = [“leet”, “code”]
Output: true
Explanation: Return true because “leetcode” can be segmented as “leet code”.
Example 2:
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:
Input: s = “catsandog”, wordDict = [“cats”, “dog”, “sand”, “and”, “cat”]
Output: false
翻译:
给定一个非空字符串s和一个包含非空单词列表的dictionary wordDict,确定是否可以将s分割为一个由一个或多个字典单词组成的空格分隔的序列。
注意:
同一词在词典中可以重复使用多次。
你可以假设字典里没有重复的单词。
示例1:
输入:s = “leetcode”, wordDict = [“leet”, “code”]
输出:true
说明:返回true,因为“leetcode”可以分割为“leetcode”。
示例2:
输入:s = “applepenapple”, wordDict = [“apple”, “pen”]
输出:true
思路:
本题使用动态规划,index是我们每次起始匹配字符串的角标,如果在wordDict集合中找到对应字符串,那么我们更新index的值,进行递归匹配。如果此角标匹配不成功,那么我们将其放入set集合,如果新的index在set集合中找到,那么该index肯定是匹配字符串不成功的。
代码:
class Solution {
public boolean work(String s,List<String> wordDict,HashSet<Integer> set,int index){ //字符串匹配成功。
if(index==s.length())
return true;
//set集合中包含此index,肯定匹配不成功,直接false
if(set.contains(index))
return false;
//等于号,是因为subString()包含前不包含尾
for(int i=index+1 ; i<=s.length() ; i++){
//得到已index为头的所有子串。
String sub=s.substring(index,i);
//集合中是否包含此子串,如包含则得到新的index继续递归。
if(wordDict.contains(sub)){
if(work(s,wordDict,set,i)){
return true;
}
//接着匹配的也不成功,也将此坐标加入不成功集合
set.add(i);
}
}
set.add(index);
return false;
}
public boolean wordBreak(String s, List<String> wordDict) {
HashSet<Integer> set= new HashSet();
return work(s,wordDict,set,0);
}
}