LeetCode 题解(Week 11):Word Break

原题目:

Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words. You may assume the dictionary does not contain duplicate words.

For example, given
s = “leetcode”,
dict = [“leet”, “code”].

Return true because “leetcode” can be segmented as “leet code”

中文大意:

给定一个字符串向量作为字典,如[“leet”,”code”],以及一个待分割的字符串,如“leetcode”问有没有办法能够将这个字符串分割成多个连续子串,使得每个子串都在字典中,如”leetcode”在这种情况下可以分割成”leet” “code”,因此是可以的

题解:

class Solution {
public:
    bool wordBreak(string s, vector<string>& wordDict) {
        int len = s.size();
        vector<vector<bool> >dp(len,vector<bool>(len,false));

        for(int j = 0 ; j < len ;j++)
        {
            for(int i = j ; i >=0 ;i--)
            {
                bool currdp = false;
                for(int k = i ;k<=j;k++)
                {
                    string currstr = s.substr(k,j-k+1);
                    bool indict = find(wordDict.begin(), wordDict.end(), currstr )!=wordDict.end();
                    if(k==0)
                        currdp = currdp |indict;
                    else
                        currdp = currdp |(indict & dp[i][k-1]);
                }
                dp[i][j] = currdp;
            }
        }

        return dp[0][len-1];
    }
};

解析:

这道题目也出现在了《算法概论》的课后习题上。基本思路是通过二维数组(向量)来保存状态,记dp[i][j] = “在下标为i到j的子串中能够分割”,在这样的前提下,dp[i][j]的计算方式是:遍历每个在i到j的整数k,判断dp[i][k]&str(k,j)是否为真,只要存在一个k使得以上表达式为真,那dp[i][j]就等于TRUE。最终答案为dp[0][len-1],len为要求的字符串长度

整个算法下来空间复杂度为O(n^2),时间复杂度为O(n^3)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值