Word Break
Description
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".
Link
Method
- Dp, record reaching current char we can find valid break
- x
Example
- 1
class Solution { public: /** * @param s: A string s * @param dict: A dictionary of words dict */ bool wordBreak(string s, unordered_set<string> &wordDict) { // write your code here // if (s.empty() || wordDict.empty()) { // return false; // } // optimizing int longestw = 0; for (string i : wordDict) { longestw = max(longestw, (int)i.size()); } int n = s.size(); vector<bool> dp(n+1, false); dp[0] = true; for (int i = 1; i <= n; ++i) { for (int j =i-1; j >= max(i-longestw, 0); --j) { if (dp[j]) { // int start = j; // int count = i-j; string tmp = s.substr(j, i-j); // if we are surely to find "true" for dp[i], can jump out of inner for if (wordDict.find(tmp) != wordDict.end()) { dp[i] = true; break; } } } } return dp[n]; } };
Similar problems
x
Tags
x