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

动态规划。m[i][j]表示子串s[i,j]能否被组合。则递推式s[i][j] = (wordDict.find(s[i,j])?true: (存在t使得s[i][t] && s[t+1][j]吗?true:false)

时间复杂度O(n^3),空间复杂度O(n^2)

class Solution {
public:
    bool wordBreak(string s, unordered_set<string>& wordDict) {
        int n = s.length();
        bool **m = new bool*[n];
        for(int i=0;i<n;i++){ m[i] = new bool[n]; memset(m[i],0,n);}
        
        for(int k=1;k<=n;k++){
            for(int i=0;i<=n-k;i++){
                int j=i+k-1;
                if(wordDict.find(s.substr(i,k))!=wordDict.end()) m[i][j] = true;
                else{
                    for(int t=i;t<j;t++) if(m[i][t] && m[t+1][j]){ m[i][j] = true; break;}
                }
            }
        }
        return m[0][n-1];
    }
};

那有没有更快的算法呢?有!

我们其实没有必要检查每个s[i,j]是否能被组合,这样会多做很多无用功。事实我们只需检查每个s[0,i]能否被组合就可以了。那有人可能会问,求m[0][i]不需要用到m[t][i]吗?

现在假设m[0][t-1]和m[t][i]都为true,那我只需找到s[t,i]子串的最后一个可被组合的单词,这个单词必然在wordDict中,不妨设这个单词的起始下标为t2,那就一定会有

m[0][t2-1]==true,所以m[0][i] = m[0][t2-1] && wordDict.find(s.substr(t2,i-t2+1)),根本无需知道m[t][i]

改进的时间复杂度O(n^2),空间复杂度O(n)


class Solution {
public:
    bool wordBreak(string s, unordered_set<string>& wordDict) {
        int n = s.length();
        bool *m = new bool[n+1];
        memset(m,0,n+1);
        m++;
        m[-1] = true; 
       
        for(int i=0;i<n;i++){
            for(int j=i-1;j>=-1;j--) 
                if(m[j] && wordDict.find(s.substr(j+1,i-j))!=wordDict.end()){
                    m[i] = true; break;
                } 
        }
        return m[n-1];
    }
};



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值