您的位置:首页 > 其它

LeetCode 139. Word Break

2016-07-03 19:17 495 查看
Problem: https://leetcode.com/problems/word-break/

Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separated sequence of one or more dictionary words.

For example, given
s =
"leetcode"
,
dict =
["leet", "code"]
.

Return true because
"leetcode"
can be segmented as
"leet code"
.

Thought:

for each position, traverse whether it is end with word in wordDict, if is ,and check position[i - len] is true. then position[i] = true

the result depend on position[s.length]

Code C++:

class Solution {
public:
bool wordBreak(string s, unordered_set<string>& wordDict) {
if (s.length() <= 0 || wordDict.size() <= 0) {
return false;
}

vector<int> check(s.length() + 1, 0);
check[0] = 1;

for (int i  = 1; i <= s.length(); i++) {
for (const string& word : wordDict) {
int len = word.length();
if (i - len >= 0 && s.substr(i-len,len) == word && check[i - len] == 1) {
check[i] = 1;
}
}
}
return check[s.length()] == 1;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: