题目描述:
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"
.
lintcode的tag写的是dp思路。刚开始我考虑的是recursion,不过如果是这么写的话估计就超时了。这也算是一题比较典型的dp,估计能想到dp,题目就解了一大半了。这里要通过时间limit,还需要注意的是,可以把之前为true的index存起来,并且遍历previous 'true index'的时候应该从后往前遍历,这样可以大大缩短搜索的时间。
Mycode (AC = 1555ms):
class Solution {
public:
/**
* @param s: A string s
* @param dict: A dictionary of words dict
*/
bool wordBreak(string s, unordered_set<string> &dict) {
// write your code here
s = " " + s;
vector<bool> dp(s.length(), false);
vector<int> true_idx;
dp[0] = true;
true_idx.push_back(0);
for (int i = 1; i < s.length(); i++) {
// store the 'true index' into a vector, so that
// each searching time just need to search all the
// previous true index
for (int k = true_idx.size() - 1; k >= 0; k--) {
int idx = true_idx[k];
string rest = s.substr(idx + 1, i - idx);
if (dict.find(rest) != dict.end()) {
dp[i] = true;
true_idx.push_back(i);
break;
}
}
}
return dp[s.length() - 1];
}
};