LeetCode OJ Word Break

本文介绍了一种判断字符串是否能被拆分为一个或多个字典中单词序列的算法,并提供了两种动态规划解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

DP:

first dp:

class Solution {
public:
    bool wordBreak(string s, unordered_set<string> &dict) {
        vector<short> isOK(s.size() + 1, 0);
        isOK[s.size()] = 1;
        for (int i = s.size() - 1; i >= 0; i--) {
            for (int j = i; j < s.size(); j++) {
                if (dict.find(s.substr(i, j - i + 1)) != dict.end() && isOK[j + 1]) {
                    isOK[i] = 1;
                    break;
                }
            }
        }
        return isOK[0];
    }
};
The thought is :
This dp is from the bottom. Suppose the string is "abcdefghijk", the word break is successful when "abcde" is in the dictionary and "fghijk" is successfully word break.
So, isOK[i] means the substr starting from i is successfully word break. In the inner loop, if we found a substr from i to j is in the dictionary and the rest substr from j + 1 to the end is OK, then isOK[i] = 1.
Notice that isOK[s.size()] = 1 because the substr is empty.
second dp:
class Solution {
public:
    bool wordBreak(string s, unordered_set<string> &dict) {
        vector<short> isOK(s.size() + 1, 0);
        isOK[0] = 1;
        for (int i = 1; i <= s.size(); i++) {
            for (int j = 1; j <= i; j++) {
                if (dict.find(s.substr(j - 1, i - j + 1)) != dict.end() && isOK[j - 1]) {
                    isOK[i] = 1;
                    break;
                }
            }
        }
        return isOK[s.size()];
    }
};
Notice that isOK[0] is just a start sign of 0 length, which is always true, so the i and j start from 1 but they both point to s[i - 1] or s[j - 1].




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值