LeetCode Word Break
Problem Description
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"
.
Problem Solution:
Note: 参照官网用的方法,DP可解决问题,即将源字符串从开始到结尾,分解成各个子串进行操作,对于这类字符串组合问题,需要掌握类似状态转移方程,代码如下:
class Solution { public: bool wordBreak(string s, unordered_set<string> &dict) { int nsize=s.size(); int i=0,j=0; bool *dp = new bool[nsize]; memset(dp,false,sizeof(dp)); for(i=0;i<nsize;++i) { dp[i] = ((dict.find(s.substr(0,i+1))!=dict.end())?true:false); if(dp[i]) continue; else { for(j=0;j<i;++j) { if(dp[j]) { dp[i] = ((dict.find(s.substr(j+1,i-j))!=dict.end())?true:false) | dp[i]; } } } } return dp[nsize-1]; delete []dp; } };
作者:ballwql
本文为作者原创,版权所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。