122_leetcode_wordBreak

本文探讨了如何使用动态规划解决字符串分割问题,通过计算字典中单词的最长和最短长度,实现字符串的合理分割。

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

1:计算dict中最长和最短单词的长度n,m;2:采用动态规划的方法,获取s中的长度为m到n(或者s的长度)字符串,检测当前字符串是否是单词,之后在检测后面的字符串是否满足题意,如果不满足,记录后面的字符串,表示已经检测过了为不满足的字符串。

    bool wordBreak(string s, unordered_set<string> &dict)
    {
        if(s.length() < 1)
            return true;
        
        if(dict.empty())
            return false;
        
        //首先获得dict中最长单词的长度和最短单词的长度
        unordered_set<string>::iterator itr = dict.begin();
        int maxLength = (int)(*itr).length();
        int minLength = (int)(*itr).length();
        
        while(++itr != dict.end())
        {
            if((*itr).length() > maxLength)
            {
                maxLength = (int)(*itr).length();
            }
            if((*itr).length() < minLength)
            {
                minLength = (int)(*itr).length();
            }
        }
        
        set<string> unMatch;
        
        return wordBreakCore(s, dict, unMatch, maxLength, minLength);
        
        return true;
    }
    
    bool wordBreakCore(string s, unordered_set<string> &dict, set<string> &unMatch, int &maxLength, int &minLength)
    {
        if(s.size() < 1)
            return true;
        
        unsigned long mx = maxLength > s.length() ? s.size() : maxLength;
        
        for(int i = (int)mx; i >= minLength; i--)
        {
            string tmpWord = s.substr(0, i);
            unordered_set<string>::iterator itr = dict.find(tmpWord);
            if(itr != dict.end())
            {
                string leftStr = s.substr(i);
                set<string>::iterator leftItr = unMatch.find(leftStr);
                if(leftItr != unMatch.end())
                {
                    continue;
                }
                else
                {
                    if(wordBreakCore(leftStr, dict, unMatch, maxLength, minLength))
                    {
                        return true;
                    }
                    else
                    {
                        unMatch.insert(leftStr);
                    }
                }
            }
        }
        
        return false;
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值