139 Word Break [Leetcode]

44 篇文章 0 订阅
3 篇文章 0 订阅

题目内容:

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>& wordDict) {
        return segmentation(s, 0, wordDict);
    }

    bool segmentation(string &s, int index, unordered_set<string>& wordDict) {
        int size(s.size());
        if(index == size)
            return true;
        for(int i = index; i < size; ++i) {
            if(wordDict.find(s.substr(index, i-index+1)) != wordDict.end() && segmentation(s, i+1, wordDict))
                return true;
        }
        return false;
    }
};

但同样,遇到
“aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab”
[“a”,”aa”,”aaa”,”aaaa”,”aaaaa”,”aaaaaa”,”aaaaaaa”,”aaaaaaaa”,”aaaaaaaaa”,”aaaaaaaaaa”]
这样的输入,会因为很多次的重复运算而超时。
而解决效率问题的做法当然就是动态规划。

动态规划:
需要把问题分解为子问题求解。可以用一个一维数组canSeparate[index]来表示从0到index的字符串能否被分割成字典中的字符。
中间过程的更新方式:
1. 如果从0到index的字符串能够在字典中找到,那么直接返回true;
2. 如果不能找到,那么从当前的index开始向前找到这样一个下标i,使得canSeparate[i]为true,并且字符串[i+1, index]能够在字典中能够找到。

代码如下,运行时间8ms:

class Solution {
public:
    bool wordBreak(string s, unordered_set<string>& wordDict) {
        int size(s.size());
        if(size == 0)
            return false;

        vector<bool> canSeparate(size, false);
        for(int i = 0; i < size; ++i) {
            if(wordDict.find(s.substr(0, i+1)) != wordDict.end())
                canSeparate[i] = true;
            else {
                for(int j = i; j > 0; --j) {
                    if(wordDict.find(s.substr(j, i-j+1)) != wordDict.end() && canSeparate[j-1]) {
                        canSeparate[i] = true;
                        break;
                    }
                }
            }
        }

        return canSeparate.back();
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值