【算法】动态规划-字符串分割

描述

给定一个字符串s和一组单词dict,判断s是否可以用空格分割成一个单词序列,使得单词序列中所有的单词都是dict中的单词(序列可以包含一个或多个单词)。

例如:
给定s=“nowcode”;
dict=["now", "code"].
返回true,因为"nowcode"可以被分割成"now code".

 拆分词句_牛客题霸_牛客网 (nowcoder.com)icon-default.png?t=M0H8https://www.nowcoder.com/practice/5f3b7bf611764c8ba7868f3ed40d6b2c?tpId=46&tqId=29041&tPage=1&rp=1&ru=/ta/leetcode&qru=/ta/leetcode/question-ranking

 思路:

 

 在求F[8]的时候不需要关心F[1]~F[7]分割的是什么,只需拿结果。

代码:

class Solution {
public:
    bool wordBreak(string s, unordered_set<string>& dict) {
        if (s.empty())
            return false;
        if (dict.empty())
            return false;

        vector<bool> F(s.size() + 1, false);
        // 初始化F(0) = true
        F[0] = true;

        for (int i = 1; i <= s.size(); ++i)
        {
            for (int j = i - 1; j >= 0; --j)
            {
                // F(i): true{j <i && F(j) && substr[j+1,i]能在词典中找到} OR false
                // 第j+1个字符的索引为j
                if (F[j] && dict.find(s.substr(j, i - j)) != dict.end())
                {
                    F[i] = true;
                    break;
                }
            }
        }
        return F[s.size()];
    }
};

猜你喜欢

转载自blog.csdn.net/m0_51866180/article/details/122878629
今日推荐