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"].
解法2:动态规划
我们定义状态数组:state[s.length()+1],state[i]代表:string[0,i-1] 可被字典中的单词分割。
状态转移方程:state[i] = {state[j]&&string[i,j]在字典中,0=<j<i}。
For example, given
s = "leetcode",
dict = ["leet", "code"].
Return true because "leetcode" can be segmented as "leet code".
判断输入的字符串能否被拆分成字典中的两个单词。
例如:输入字符串"cars" 字典:"car", “ca”, "rs", 返回:true。
解题报告:
解法1:DFS,直接深搜,而且本题不要求字典中的单词唯一,所以DFS过程中不需要改变字典。但大数据TLE。
public class Solution {
public boolean wordBreak(String s, Set<String> dict) {
if(dict.size()==0) {
return false;
}
Iterator<String> it = dict.iterator();
while (it.hasNext()) {
String str = it.next();
if(s.equals(str)) {
return true;
}
if(s.indexOf(str)==0) {
if(wordBreak(s.substring(str.length()),dict)==true) {
return true;
}
}
}
return false;
}
}
解法2:动态规划
我们定义状态数组:state[s.length()+1],state[i]代表:string[0,i-1] 可被字典中的单词分割。
状态转移方程:state[i] = {state[j]&&string[i,j]在字典中,0=<j<i}。
public boolean wordBreak(String s, Set<String> dict) {
if(dict.isEmpty()) {
return false;
}
if(s.length()==0) {
return true;
}
int[] state = new int[s.length() + 1];
state[0] = 1;
for(int i=1;i<=s.length();i++) {
for(int j=0;j<i;j++) {
if(state[j]==1&&(dict.contains(s.substring(j,i))==true)) {
state[i] = 1;
break;
}
}
}
if(state[s.length()]==1) {
return true;
} else {
return false;
}
}