139. Word Break

2018-04-07  本文已影响4人  衣介书生

题目分析

Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words. You may assume the dictionary does not contain duplicate words.

For example, given
s = "leetcode",
dict = ["leet", "code"].

Return true because "leetcode" can be segmented as "leet code".

UPDATE (2017/1/4):
The wordDict parameter had been changed to a list of strings (instead of a set of strings). Please reload the code definition to get the latest changes.

代码

class Solution {
    public boolean wordBreak(String s, List<String> wordDict) {
        boolean[] dp = new boolean[s.length() + 1];
        Arrays.fill(dp, false);
        dp[s.length()] = true;
        for(int i = s.length() - 1; i >= 0; i--) {
            for(int j = i; j < s.length(); j++) {
                String subStr = s.substring(i, j + 1);
                // 当前子字符串在字典中,并且当前字符串后面的字符串也在字典中
                // 再加上从后向前遍历,就可以依次保证
                if(wordDict.contains(subStr) && dp[j+1] == true) {
                    dp[i] = true;
                    break;
                }
            }
        }
        return dp[0];
    }
}
上一篇下一篇

猜你喜欢

热点阅读