[LintCode] Word Break
Given a string s and a dictionary of words dict, determine if s can be break into a space-separated sequence of one or more dictionary words.
Example
Given s = "lintcode"
, dict = ["lint", "code"]
.
Return true because "lintcode" can be break as "lint code"
.
Solution:
DP.
bool wordBreak(string s, unordered_set<string> &dict) { int len = s.size(); if(len == 0) return true; int min_len = INT_MAX, max_len = INT_MIN; for (auto &ss : dict) { min_len = min(min_len, (int)ss.length()); max_len = max(max_len, (int)ss.length()); } vector<int> breakIdx; breakIdx.push_back(-1); for(int i = 0;i < len;++i){ for(int j = breakIdx.size() - 1;j >= 0;--j){ int idx = breakIdx[j]; if(i - idx < min_len || i - idx > max_len) continue; string str = s.substr(idx + 1, i - idx); if(dict.find(str) != dict.end()){ breakIdx.push_back(i); break; } } } return (*breakIdx.rbegin()) == (len - 1); }