Press "Enter" to skip to content

# 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 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;
};

Mission News Theme by Compete Themes.