leetcode 139. Word Break

来源:互联网 发布:软件开发 工作经验 编辑:程序博客网 时间:2024/06/07 23:37

139. Word Break

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.

解法

动态规划

  • 状态:state[i]代表第i位(第1,2,3…位)之前的字符串是否包含在字典中。

  • 初始化:定义一个长度为s.length()+1的数组。state[0] = true

  • 转移函数:state[i] = state[j] && String[j, i] (s.subString(j, i))在字典中,其中 0 <= j < i

public class Solution {    public boolean wordBreak(String s, List<String> wordDict) {        if (s.length() == 0 || s == null) {            return false;        }        if (wordDict == null || wordDict.size() == 0) {            return false;        }        // state        boolean[] state = new boolean[s.length() + 1];        state[0] = true;        for (int i = 1; i <= s.length(); i++) {            for (int j = 0; j < i; j++) {                String sub = s.substring(j, i);                // function                if (state[j] == true && wordDict.contains(sub)) {                    state[i] = true;                }            }        }        if (state[s.length()] == true) {            return true;        } else {            return false;        }        }}

这里写图片描述