题目一:word-break
Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separated sequence of one or more dictionary words.
For example, given
s ="leetcode",
dict =["leet", "code"].
Return true because"leetcode"can be segmented as"leet code".
思路:
1.动态规划,利用dp保存状态,将字符串切割成小段
2.双层循环,判断当前是否能被有效分隔
代码:
import java.util.*;
public class Solution {
public boolean wordBreak(String s, Set<String> dict) {
boolean[] dp = new boolean[s.length()+1];
dp[0] = true;
for(int i=1; i<=s.length(); i++)
{
for(int j=0; j<i; j++)
{
if(dp[j] && dict.contains(s.substring(j,i)))
{
dp[i] = true;
}
}
}
return dp[s.length()];
}
}
Given a string s and a dictionary of words dict, add spaces in s to construct a sentence where each word is a valid dictionary word.
Return all such possible sentences.
For example, given
s ="catsanddog",
dict =["cat", "cats", "and", "sand", "dog"].
A solution is["cats and dog", "cat sand dog"].
思路:
1.将字符串递归分成左右两个部分s1,s2.若s1在字典里,则递归计算s2
2.当s2无法分割时,返回空ArrayList
3.当返回的ArrayList不为空是,将结果保存到ret
4.用map来记录递归状态,用于递归结束条件
代码:
import java.util.*;
public class Solution {
Map<String, ArrayList<String>> map = new HashMap<String, ArrayList<String>>();
public ArrayList<String> wordBreak(String s, Set<String> dict) {
if(map.containsKey(s))
return map.get(s);
ArrayList<String> ret = new ArrayList<String>();
if(dict.contains(s))
ret.add(s);
for(int i=0; i<s.length(); i++)
{
String cur = s.substring(i);
if(dict.contains(cur))
{
ArrayList<String> strs = wordBreak(s.substring(0,i), dict);
if(strs.size() > 0)
{
for(String str : strs)
{
ret.add(str + " " + cur);
}
}
}
}
map.put(s,ret);
return ret;
}
}