[leetcode]139. Word Break

本文介绍了一种使用动态规划解决字符串分词问题的方法。通过给定的字符串和词典,判断该字符串是否能被分割成一个或多个词典中存在的单词序列。文章详细解释了算法原理,并提供了具体的C++实现代码。

摘要生成于 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".

Subscribe to see which companies asked this question


分析:动态规划,v[i]表示第i个字母不包括这个之前能否被分词;对于比i小的任意一个j,如果j到i的单词在dict内,且v[j]为true,那么v[i]就可以判断为true。

代码:

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值