Press "Enter" to skip to content

花花酱 Leetcode 139. Word Break

Problem

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.

 

Idea:

DP

Time complexity O(n^2)

Space complexity O(n^2)

Solutions:

C++

C++ V2 without using dict. Updated: 1/9/2018

 

Java

Python

 

请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.

Buy anything from Amazon to support our website
您可以通过在亚马逊上购物(任意商品)来支持我们

Paypal
Venmo
huahualeetcode
微信打赏

One Comment

  1. longspring longspring June 9, 2018

    More clear code below FYI.

    class Solution {
    public:
    bool wordBreak(string s, vector& wordDict) {
    for (auto word : wordDict)
    m.emplace(word, true);
    return wBreak(s, wordDict);
    }

    bool wBreak(string &s, vector& wordDict) {
    if (m.count(s)) return m[s];

    for (auto word : wordDict) {
    string left = s.substr(0, word.size());
    if (!m.count(left) || m[left] == false) continue;

    string right = s.substr(word.size());
    if (wBreak(right, wordDict)) return m[s]=true;
    }
    return m[s]=false;
    }
    private:
    unordered_map m;
    };

Leave a Reply