首页 > 其他 > 详细

139. Word Break

时间:2016-09-17 11:53:49      阅读:219      评论:0      收藏:0      [点我收藏+]

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

原文:http://www.cnblogs.com/Machelsky/p/5878175.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!