zoukankan      html  css  js  c++  java
  • Word Break

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

    题意:给一字符串和一单词集合,如果字符串可以分解成单词都在集合中,返回true。

    思路:这道题如果暴力解决或者递归解决都有可能超时,仔细思考一下,发现存在DP规则。dp[i]表示s[0,i)之间存在划分使分割后的字符串在dict里。

    初始状态:dp[0]=true;动态规则:如果s[0,i)在dict里,dp[i]=true;如果dp[j]=true即s[0,j)存在dict里且s[j,i)也在dict里,则dp[i]=true;其他条件,dp[i]=false.

    class Solution {
    public:
        bool wordBreak(string s, unordered_set<string> &dict) {
            int n=s.size();
            if(n==0)
                return true;
            vector<bool> dp(n+1,false);
            dp[0]=true;
            for(int i=1;i<=n;i++)
            {
                for(int j=i-1;j>=0;j--)
                {
                    if(dp[j] && dict.find(s.substr(j,i-j))!=dict.end())
                    {
                        dp[i]=true;
                        break;
                    }
                }
            }
            return dp[n];
        }
    };
  • 相关阅读:
    ansible-思维导图
    linux运维面试精华题
    python博客大全
    python-常用代码
    男孩周末班-k8s-架构图
    jQuery操作
    js点击事件,添加或删除元素,定时器
    js.DOM操作
    js数组,阶乘,递归,冒泡排序
    js匿名和自执行函数,控制语句
  • 原文地址:https://www.cnblogs.com/awy-blog/p/3798334.html
Copyright © 2011-2022 走看看