美文网首页
139. Word Break

139. Word Break

作者: 衣介书生 | 来源:发表于2018-04-07 21:54 被阅读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];
        }
    }
    

    相关文章

      网友评论

          本文标题:139. Word Break

          本文链接:https://www.haomeiwen.com/subject/zywscftx.html