Word Break (LeetCode)
Question:
https://oj.leetcode.com/problems/word-break/
解答:
到当前点的字符串能不能分成words依赖于:
到以前点的字符串能分成words并且以前点之后到当前点是一个有效的word,所以容易想到用DP。
DP[i] = (DP[j] && substr(j+1, i) 属于dict) for any j from 0 to i-1
class Solution { public: bool wordBreak(string s, unordered_set<string> &dict) { int n = s.size(); if (n == 0) return false; vector<bool> dp(n, false); for (int i = 0; i < n; i++) { if (dict.find(s.substr(0, i+1)) != dict.end()) { dp[i] = true; } else { for (int j = 0; j < i; j++) { if (dp[j] && dict.find(s.substr(j+1, i-j)) != dict.end()) { dp[i] = true; break; } } } } return dp[n-1]; } };