首页 > 代码库 > 139. Word Break

139. 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".

 思路:recursion。没有加if(s.equals(""))的时候一直报错,想了想终于明白为什么。像code最后是contains,进入另一层循环如果没有base case直接跳出到for循环,return false。注意base case。

public class Solution {    public boolean wordBreak(String s, Set<String> wordDict) {        if(s==null||wordDict==null)        {            return false;        }        if(s.equals(""))        {            return true;        }        for(int i=0;i<s.length();i++)        {             if(wordDict.contains(s.substring(0,i+1)))             {                 if(wordBreak(s.substring(i+1),wordDict))                 {                     return true;                 }                 else                 {                     wordDict.remove(s.substring(0,i+1));                 }             }        }        return false;            }}

 

139. Word Break