LeetCode139—Word Break

素颜马尾好姑娘i 2022-09-26 02:25 237阅读 0赞

1.原题

原题链接

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”.


2.分析

网上主流的两种说法,DP和DFS,DP将来补充,自己用DFS写的。比如说:

s=”LeetCode” dict={“Leet”,”Code”}

就从s[0]开始,”L” ,”Le”, “Lee”,”Leet” 当找到匹配项时,重新设定起始位置,从剩下的子串开始搜索。

这个思路最后会超时。

不过可以记录一下,DFS返回时字符串中不满足条件的位置的索引添加到容器中。

代码

  1. class Solution {
  2. private:
  3. unordered_set<int>index;
  4. bool dfs(string s, unordered_set<string>&wordDict,int start)
  5. {
  6. if (start==s.size())//DFS返回
  7. return true;
  8. if (index.find(start) != index.end())//不满足条件的索引
  9. return false;
  10. for (int i = 1; i <= s.size()-start; i++)
  11. {
  12. string sub = s.substr(start, i);
  13. if (wordDict.find(sub) != wordDict.end())
  14. {
  15. if (dfs(s, wordDict, start+i))
  16. return true;
  17. else
  18. index.insert(start+i);//将不满足条件的索引添加到容器中
  19. }
  20. }
  21. return false;
  22. }
  23. public:
  24. bool wordBreak(string s, unordered_set<string>& wordDict) {
  25. return dfs(s, wordDict,0);
  26. }
  27. };

发表评论

表情:
评论列表 (有 0 条评论,237人围观)

还没有评论,来说两句吧...

相关阅读

    相关 139.Word Break(断字符串)

    题目: 给定一个非空字符串s和包含非空单词列表的字典wordDict,请确定s是否可以分段为一个或多个字典单词的以空格分隔的序列。 注意: 字典中的同一单词可以在分割