word break

1 Star2 Stars3 Stars4 Stars5 Stars 給文章打分!

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. You may assume the dictionary does not contain duplicate words.
For example, given
s = "leetcode",
dict = ["leet", "code"].
Return true because "leetcode" can be segmented as "leet code".

public class Solution {
// shoudl consider input, wordDict is small, check through string s
//  O(n*m)  m for small Dict
public boolean wordBreak(String s, List<String> wordDict) {
boolean[] canBreak = new boolean[s.length()   1]; // s can be break from start to i;
canBreak[0] = true;
for(int i=0; i<= s.length(); i  ){
if(!canBreak[i]) continue;
for(String word : wordDict) {   // renew each possible position with true
int len = word.length();
int end = i   len;
// those unreachable position and reached position should ignore
if(end > s.length() || canBreak[end]) continue;
canBreak[end] = true;
return canBreak[s.length()];

//Second DP
put list<String> into Set<String>           
O(n^2) time two nested for loop
O(K) for Dict
for(int i=1; i <= s.length(); i  ){         // fix the ending, find the starting, then compare middle
for(int j=0; j < i; j  ){
if(f[j] && dict.contains(s.substring(j, i))){
f[i] = true;


程式語言 最新文章