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".
這道題還是挺有難度的。重點是dynamic PRogramming的應用。用boolean[]來判斷true/false與否。記得除了contians()的條件外還要判斷兩個被分開的單詞是否連在一起這樣的問題。
代碼如下。~
public class Solution {    public boolean wordBreak(String s, Set<String> wordDict) {        if(s==null&&s.length()==0){            return false;        }        int len=s.length();                boolean[] test=new boolean[len];        for(int i=0;i<len;i++){            for(int j=0;j<=i;j++){               String sub=s.substring(j,i+1);               if(wordDict.contains(sub)&&(j==0||test[j-1])){                   test[i]=true;                   break;               }            }        }        return test[len-1];    }}
 
  | 
新聞熱點
疑難解答