zoukankan      html  css  js  c++  java
  • 139. 单词拆分. dp

    给定一个非空字符串 s 和一个包含非空单词列表的字典 wordDict,判定 s 是否可以被空格拆分为一个或多个在字典中出现的单词。

    说明:

    拆分时可以重复使用字典中的单词。
    你可以假设字典中没有重复的单词。
    示例 1:

    输入: s = "leetcode", wordDict = ["leet", "code"]
    输出: true
    解释: 返回 true 因为 "leetcode" 可以被拆分成 "leet code"。
    示例 2:

    输入: s = "applepenapple", wordDict = ["apple", "pen"]
    输出: true
    解释: 返回 true 因为 "applepenapple" 可以被拆分成 "apple pen apple"。
      注意你可以重复使用字典中的单词。
    示例 3:

    输入: s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"]
    输出: false

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/word-break
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    class Solution {
    public:
        bool wordBreak(string s, vector<string>& wordDict) {
            int n = s.size();
            //dp[i]表示字符串s的前i个字符能否拆分成wordDict。
            vector <bool> dp (n + 1, false);
            unordered_set <string> m(wordDict.begin(), wordDict.end());
    
            dp[0] = true;
            //遍历起始位置
            for (int i = 1; i <= n; i++){
                //遍历长度
                for (int j = 0; j < i; j++){
                    if (dp[j] && m.find(s.substr(j, i - j)) != m.end()){
                        dp[i] = true;
                        break;
                    }
                }
            }
    
            return dp[n];
        }
    };
    

    优化
    每次并不需要从s[0]开始搜索。因为wordDict中的字符串长度是有限的。只需要从i-maxWordLength开始搜索就可以了。

    class Solution {
    public:
        bool wordBreak(string s, vector<string>& wordDict) {
            int n = s.size();
            //dp[i]表示字符串s的前i个字符能否拆分成wordDict。
            vector <bool> dp (n + 1, false);
            unordered_set <string> m(wordDict.begin(), wordDict.end());
    
            int maxLength = 0;
            for (auto word : wordDict){
                maxLength = max(maxLength, (int)word.size());
            }
    
            dp[0] = true;
            //遍历起始位置
            for (int i = 1; i <= n; i++){
                //遍历长度
                for (int j = max(i - maxLength, 0); j < i; j++){
                    if (dp[j] && m.find(s.substr(j, i - j)) != m.end()){
                        dp[i] = true;
                        break;
                    }
                }
            }
    
            return dp[n];
        }
    };
    
  • 相关阅读:
    Mysql常见索引介绍
    Mysql字段修饰符(约束)
    使用select和show命令查看mysql数据库系统信息
    Mysql5.7数据库介绍
    对Mysql数据表本身进行操作
    各种修改Mysql字符集
    Mysql的安全配置向导命令mysql_secure_installation
    firewalld介绍
    CentOS7使用yum安装mysql5.7
    利用ASP.NET一般处理程序动态生成Web图像(转)
  • 原文地址:https://www.cnblogs.com/xgbt/p/13191497.html
Copyright © 2011-2022 走看看