标签:style blog http io ar color os sp for
给一个字符串,判断是否能够分为若干个部分,并且每个部分都能在字典dict里面找到。有的话就返回true。例如:
For example, given
s = "leetcode"
,
dict = ["leet", "code"]
.
Return true because "leetcode"
can be segmented as "leet code"
.
class Solution { public: bool wordBreak(string s, unordered_set<string> &dict) { bool dp[s.size()]; memset(dp, 0, sizeof(dp)); for (int i = 0; i < s.size(); i++) { if (dict.count(s.substr(i, s.size() - i))) dp[i] = 1; } for (int i = s.size() - 1; i < s.size(); i--) { if (dp[i] == false) { for (int j = i; j < s.size(); j++) { if (dict.count(s.substr(i, j - i + 1)) && dp[j + 1]) dp[i] = true; if (dp[i]) break; } } } return dp[0]; } };
这题好像个之前做过的leetcode Palindrome Partitioning II有相似的地方。这题比它容易一些。
标签:style blog http io ar color os sp for
原文地址:http://www.cnblogs.com/higerzhang/p/4159775.html