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;
        
    }
}

 

posted on 2016-09-17 11:26  Machelsky  阅读(278)  评论(0)    收藏  举报