LeetCode 139. Word Break 原创Java参考解答

LeetCode 139. Word Break 原创Java参考解答

问题描述

https://leetcode.com/problems/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.

解题思路

题目是求一个字符串s是否能切分出所有wordDict里面的单词。

判断方案是否可行的题目则有很大可能是动态规划题,本题亦如此。

本题的动态规划方程f[i]: 表示s的前i个位置能否切分出wordDict里面的单词。初始化时,f[0]为true,表示空字符串””也是在wordDict里的单词。

二重循环,j < i,用来计算s字符串第 i 位置能否切出wordDict里面的单词。

  • f[j] 用来获取s的前 j 个位置是否能切出wordDict里面的单词。
  • 只有当f[j] = true(即s前 j 个字符能切出单词)并且s.substring(j, i) 也是在wordDict里面单词的时候,表明s的第 i 位置可以切分。

参考代码

public class Solution {
    public boolean wordBreak(String s, List<String> wordDict) {
        // f(x): whether the i th position of s is able to make word break
        boolean[] f = new boolean[s.length() + 1];
        f[0] = true;
        
        for (int i = 0; i < s.length() + 1; i++) {
            for (int j = 0; j < i; j++) {
                if (!f[j]) {
                    continue;
                }
                
                String sub = s.substring(j, i);
                if (wordDict.contains(sub)) {
                    f[i] = true;
                    break;
                }
            }
        }
        
        return f[s.length()];
    }
}

相关题目

LeetCode All in One 原创题目讲解汇总

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注