码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode笔记:Word Break

时间:2018-01-23 10:48:09      阅读:119      评论:0      收藏:0      [点我收藏+]

标签:状态转移方程   leetcode   determine   comm   数组   because   span   lin   enc   

一. 题目描写叙述

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

二. 题目分析

假设使用递归,会超时。

这时使用动态规划就可以解决这个问题,即将源字符串s从開始到结尾。分解成各个子串进行操作,对于这类字符串组合问题,须要掌握相似状态转移方程。

对于下标i所相应字符的匹配状态flag[i],假设dict有字符串能够匹配,这取决于之前某个字符j的状态出现匹配。从数组s的j + 1i下标之间的字符也能从dict中找到匹配的字符串:

flag[i] = any(flag[j] && (s[j + 1, i] ∈ dict))

三. 演示样例代码

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

四. 小结

动态规划对于解决一些字符串的问题也是有效且easy实现的。

leetcode笔记:Word Break

标签:状态转移方程   leetcode   determine   comm   数组   because   span   lin   enc   

原文地址:https://www.cnblogs.com/llguanli/p/8334015.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!