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".
class Solution {
public:
bool wordBreak(string s, unordered_set<string> &dict) {
int n = s.size();
vector<bool> p(n + 1,false);
p[0] = true;
for(int i = 0;i < n;i ++){
if(p[i]){
for(int step = 1;i + step - 1 < n;step ++){
if(dict.count(s.substr(i,step)) > 0)
p[i + step] = true;
}
}
}
return p[n];
}
};
本文深入探讨了如何通过编程技巧将给定字符串分割为一系列字典中存在的单词,具体以实例‘leetcode’为例,展示了利用C++实现的解决方案。此方法对于文本解析、自然语言处理等领域具有重要意义。
1593

被折叠的 条评论
为什么被折叠?



