LeetCode OJ:Word Break

来源:互联网 发布:dbc数据库详解 编辑:程序博客网 时间:2024/06/06 23:28

Word Break

 Total Accepted: 5921 Total Submissions: 31188My Submissions

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

算法思想:动态规划

dp[i]表示从i到len-1位置是否可以被分割成字典中的单词,所以,只要确定一组,当i<=j<len时,从i到j的子字串是字典中的单词,同时dp[j+1]=true,即j+1到len-1位置可以被分割,那么dp[i]就为true

class Solution{public:bool wordBreak(string s, unordered_set<string> &dict) {int len=s.length();vector<bool> dp(len+1,false);dp[len]=true;for(int i=len-1;i>=0;i--)for(int j=i;j<len;j++){string str=s.substr(i,j-i+1);if(dict.find(str)!=dict.end()&&dp[j+1]){dp[i]=true;break;}}return dp[0];}};



0 0
原创粉丝点击