Leetcode刷题之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".

解答这道题我首先想到的是递归去做,以下是我写的代码:

class Solution {
public:
    bool wordBreak(string s, unordered_set<string> &dict) 
	{
		for(int i = 1;i<=s.size();++i)
		{
			if(dict.count(s.substr(0,i)))
			{
				if(i == s.size())
					return true;
				if(wordBreak(s.substr(i+1,s.size()-i),dict))
					return true;
			}
		}
		return false;
    }
	
};

但是提示我 Time Limit Exceeded。。好吧,其实一路联系过来,我对DFS、BFS算法都算了解的比较多了,所以遇到这类问题一般想这么去解决了。看了网上其他人的解答,原来这道题可以用DP算法来做。

class Solution {
  public:
     bool wordBreak(string s, unordered_set<string> &dict) {
          int n = (int)s.size();
          vector<bool> dp(n + 1, false);
          dp[0] = true;
          for (int i = 0; i < n; i++) {
              if (dp[i]) {
                  for (int len = 1; i + len - 1 < n; len++) {
                     if (dict.count(s.substr(i, len)) > 0)
                         dp[i + len] = true;
                 }
             }
         }
         return dp[n];
     }
 };

通过这道题,我明白自己还是对DP算法理解的不够深刻。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值