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];
        }
    };
  • 相关阅读:
    MySQL主从半同步复制
    MySQL主从之延时复制
    MySQL备份
    MySQL主从介绍及搭建(异步复制)
    MySQL物理备份Xtrabackup
    MySQL数据库误删除数据恢复
    MySQL--日志
    JAVA日报
    JAVA日报
    JAVA日报
  • 原文地址:https://www.cnblogs.com/awy-blog/p/3798334.html
Copyright © 2011-2022 走看看