[Leetcode Week9]Word Break

本文介绍了一种利用动态规划解决 LeetCode 上 WordBreak 问题的方法。该方法通过生成源字符串的所有子串并在词典中查找这些子串来判断原始字符串是否能被分割为词典中的词汇。

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

Word Break 题解

原创文章,拒绝转载

题目来源:https://leetcode.com/problems/word-break/description/


Description

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

Solution

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

解题描述

这道题采用的是动态规划的方式进行求解。将整个问题化成小问题:生成来源字符串的所有子串,并在词典中查找字串,如果存在则进行标记,之后查看所有的这些字串能否连起来组成原来的字符串。

转载于:https://www.cnblogs.com/yanhewu/p/7768078.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值