Given a stringSAnd a dictionary of wordsDict, Determine ifSCan 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"leet code".
Dynamic Programming. Use a table to record 0 ~ Whether the I-1 meets the requirements. Note that the first table [0] = true, and the table length is the length of the input string plus one. Loop 0 ~ S. Length ()-1, which can only start from where Table [I] = true, because it is matched before it can be matched.
public class Solution { public boolean wordBreak(String s, Set<String> dict) { int strlen=s.length(); boolean [] table=new boolean[strlen+1]; table[0]=true;//begin is always true, so we can start the loop for(int i=0;i<strlen;i++){ if(!table[i])// 0~i-1 are not words continue; for(String word: dict){ int len=word.length(); int end=i+len-1; if(end>strlen-1) continue; if(table[end+1])//already match at this position continue; if(s.substring(i,end+1).equals(word)){ table[end+1]=true; } } } return table[strlen]; }}