题目链接地址:https://oj.leetcode.com/problems/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"
.
决解思想:
.在这道题中,给定一个set集合当成字典,在给一个String,然后在set中找到单词能组合成String这个字符串,如果能够找到,返回true,否则返回false。在以前提交的算法中采用递归的思想来做,但是会超时,原因是重复查找了一部分,因此应该设置一个数组来记忆已经有多少已经匹配成功了,当字符串扫描完成后,返回boolean类型数组的最后一个值即可。
代码如下;
class Solution7 {
public boolean wordBreak(String s, Set<String> dict) {
boolean[] state = new boolean[s.length()+1];
state[0] = true;
for(int i=0; i<s.length(); i++){
if(!state[i])
continue;
for(String a: dict){
int len = a.length();
int end = i + len;
if(end > s.length())
continue;
//if t[end]=true 说明end以前的已经匹配完成不用重复匹配
if(state[end]) continue;
if(s.substring(i, end).equals(a)){
state[end] = true;
}
}
}
return state[s.length()];
}
}