word-break-ii

本文介绍了一种基于字典匹配的字符串拆分算法,通过构建二维矩阵记录子串的有效性,并采用递归方式生成所有可能的合法句子组合。

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

  • 题目:Given a string s and a dictionary of words dict, add spaces in s to construct a sentence where each word is a valid dictionary word.

    Return all such possible sentences.

    For example, given
    s =“catsanddog”,
    dict =[“cat”, “cats”, “and”, “sand”, “dog”].

    A solution is[“cats and dog”, “cat sand dog”].

  • idea:

    1. 首先建立一个二维矩阵match来记录字符串中的字串是否在dict里,如match[i][j]表示字串i…j是否在dict里。
    2. 从字符串结尾处开始逆序遍历,如果begin到end在字典里,则判断0到begin是否也是一个句子。如果end==-1,那么cur_str就是一个句子,将cur_str添加到ans;否则不是一个句子,不用添加到ans
    3. 使用cur_str记录当前string,如果begin到end的字串属于dict,则push_back到cur_str。递归返回后,需要将cur_str使用pop_back(),尝试下一种可能性。
  • code

#include <bits/stdc++.h>
class Solution {
public:
    vector<string> wordBreak(string s, unordered_set<string> &dict) {
        vector<string> ans;
        const size_t len = s.size();
        bool **match = (bool**)malloc(sizeof(bool*)*len);
        for (int i = 0; i < len; i++){
            //match[i] = (bool*)malloc(sizeof(bool)*len);
            match[i] = new bool[len];
        }
        
        /*
            make the match matrix, in which match[i][j] represents whether substring of s
            from i to j is a word of dict
        */
        for (int i = 0; i < len; i++){
            for (int j = i; j < len; j++){
                if (dict.find(s.substr(i, j-i+1)) != dict.end())
                    match[i][j] = true;
                else match[i][j] = false;
            }
        }
        vector<string> cur_str;
        
        //make sentences according to the match matrix recursively.
        make_sentence(s, len-1, ans, match, cur_str);
        return ans;
    }
    
    void make_sentence(string s, int end, vector<string> &ans, bool **match, vector<string> &cur_str){
        if (end<0){
            unsigned len = cur_str.size();
            string sentence = cur_str[0];
            for (int i = 1; i < len; i++){
                sentence = cur_str[i] + " " + sentence;
            }
            ans.push_back(sentence);
            return;
        }
        
        for (int begin = end; begin>-1; --begin){
            if (match[begin][end]){
                cur_str.push_back(s.substr(begin, end-begin+1));
                make_sentence(s, begin-1, ans, match, cur_str);
                cur_str.pop_back();
            }
        }
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值