Leetcode:Word Break

来源:互联网 发布:c语言用户标识符的 编辑:程序博客网 时间:2024/04/27 16:20

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

动态规划,字符串i个字母有解的充要条件是,存在数字k,使前k个字母有解,且substr(k+1,i)是字典里的元素。

实现代码:

class Solution {public:    bool wordBreak(string s, unordered_set<string> &dict) {        // Note: The Solution object is instantiated only once and is reused by each test case.        int n = (int)s.size();vector<bool> dp(n + 1, false);dp[0]=true;for(int i=1;i<=n;i++){if(dp[i-1]){int idx=i-1;for(int j=idx+1;j<=n;j++){string cur=s.substr(idx,j-idx);if(dict.count(cur)>0)dp[j]=true;}}}return dp[n];}};


0 0
原创粉丝点击