leetcode:Word Break

转自:http://blog.csdn.net/liushu1231/article/details/23393955

题目】

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

【解法】

看到这道题,第一反应就是深搜,暴力解法,代码如下:

[cpp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. bool wordBreak(string s, unordered_set<string> &dict) {  
  2.         auto it = dict.find(s);  
  3.        if(it != dict.end()){  
  4.             return true;  
  5.         }  
  6.         for(int i = 0; i < s.length(); i++){  
  7.             string str1 = s.substr(0,i);  
  8.             string str2 = s.substr(i+1,s.length());  
  9.             if(wordBreak(str1,dict) && wordBreak(str2,dict))  
  10.                 return true;  
  11.         }  
  12.         return false;  
  13.     }  
提交之后直接超时,然后分析发现其实是可以用dp去解决的,dp最主要的思想是找到重复子问题,推出状态方程,我们看这道题的状态方程,其实跟其他dp算法还是有点区别的,状态方程为f(i) = 存在j 使得f(j) && s[j+1,i]属于dict ,那么可以写出代码:

[cpp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. bool wordBreak(string s,unordered_set<string> &dict){  
  2.         vector<bool> f(s.length()+1,false);  
  3.         f[0] = true;  
  4.         for(int i = 1; i < s.length()+1 ;i ++){  
  5.             for (int j = i-1; j >= 0; j--){  
  6.                 if(f[j] && (dict.find(s.substr(j,i-j))!=dict.end())){//注意substr的用法,substr(pos,len)  
  7.                     f[i] = true;  
  8.                 }  
  9.             }  
  10.         }  
  11.         return f[f.size()-1];  
  12.     }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值