139 Word Break 单词拆分

给定一个非空字符串 s 和一个包含非空单词列表的字典 wordDict,确定 s 是否可以被空格分割为一个或多个在字典里出现的单词。你可以假设字典中无重复的单词。
例如,给出
s = "leetcode",
dict = ["leet", "code"]。
返回 true 因为 "leetcode" 可以被切分成 "leet code"。

详见:https://leetcode.com/problems/word-break/description/

Java实现:

class Solution {
    public boolean wordBreak(String s, List<String> wordDict) {
        int n=s.length();
        //dp[i]表示前i个字符能不能被dict完美划分
        boolean[] dp=new boolean[n+1];
        dp[0]=true;
        for(int i=1;i<=n;++i){
            for(int j=0;j<i;++j){
                //substring是前闭后开
                String tmp=s.substring(j,i);
                if(dp[j]&&wordDict.contains(tmp)){
                    dp[i]=true;
                    break;
                }
            }
        }
        return dp[n];
    }
}

参考:http://www.cnblogs.com/grandyang/p/4257740.html

posted on 2018-04-05 23:26  lina2014  阅读(133)  评论(0编辑  收藏  举报

导航