LeetCode-139. Word Break

网友投稿 602 2022-11-09

LeetCode-139. Word Break

LeetCode-139. Word Break

Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words.

Note:

The same word in the dictionary may be reused multiple times in the segmentation.You may assume the dictionary does not contain duplicate words.

Example 1:

Input: s = "leetcode", wordDict = ["leet", "code"] Output: true Explanation: Return true because ​​"leetcode"​​​ can be segmented as ​​"leet code"​​.

Example 2:

Input: s = "applepenapple", wordDict = ["apple", "pen"] Output: true Explanation: Return true because ​​"applepenapple"​​​ can be segmented as ​​"apple pen apple"​​.   Note that you are allowed to reuse a dictionary word.

Example 3:

Input: s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"]Output: false

题解:

dp,使用set保存数据加快查找速度

class Solution {public: bool wordBreak(string s, vector &dict) { int n = s.length(); int m = dict.size(); unordered_set st(dict.begin(), dict.end()); if (n == 0 || m == 0) { return false; } if (st.find(s) != st.end()) { return true; } vector dp(n + 1, false); dp[0] = true; for (int i = 0; i < n; i++) { for (int j = 1; j <= n - i; j++) { if (dp[i + j] == true) { continue; } if (st.find(s.substr(i, j)) != st.end()) { dp[i + j] = dp[i]; } } } return dp[n]; }};

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:HUST-找位置
下一篇:LeetCode-200. Number of Islands
相关文章

 发表评论

暂时没有评论,来抢沙发吧~