Leetcode_word-break(c++ and python version)

62 篇文章 0 订阅
52 篇文章 0 订阅

地址:http://oj.leetcode.com/problems/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".

思路:一拿起来条件反射dfs果断TLE了,还是应该用动态规划啊啊啊。

动态规划子状态:在长为s.length()的数组中的某个地址x上,当dp[x]为true时(意味着s的到x为止的长度都可以由给定字典拼成),可以有状态转移。

动态规划状态转移:dp[x]为true根据字典判断出x之后的为true的位置y,当s.substr(x, y-x)存在字典中时,有dp[y]为true。

参考代码 c++:

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


Second trial, in C++

//Second trial, almost the same
class Solution {
public:
    bool wordBreak(string s, unordered_set<string> &dict) {
        if(s.empty() || dict.empty())
            return NULL;
        vector<bool>dp(s.length()+1, false);
        dp[0] = true;
        int wlen;
        for(int i = 0; i<s.length(); ++i) {
            for(auto it = dict.begin(); it != dict.end(); ++it) {
                wlen = (*it).length();
                if(dp[i]) {
                    if(i + wlen <= s.length() && s.substr(i, wlen)==*it)
                        dp[i+wlen] = true;
                }
            }
            if(dp[s.length()])
                return true;
        }
        return false;
    }
};



Python:

class Solution:
    # @param s, a string
    # @param dict, a set of string
    # @return a boolean
    def wordBreak(self, s, dict):
        if not s or not len(dict):
            return False
        dp = [True] + [False] * len(s)
        for i in range(len(dp)):
            for word in dict:
                if dp[i] and i+len(word) <= len(s) and s[i:i+len(word)]==word :
                    dp[i+len(word)] = True
            if dp[len(s)]:
                return True
        return False


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值