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];
        }
    };
    
  • 相关阅读:
    西门子PLC 8种入门实例接线与控制
    安全继电器工作原理、接线图、使用方法图解
    RKNN--群聊天
    技术分享 | 无人机上仅使用CPU实时运行Yolov5?(OpenVINO帮你实现)(上篇)
    (博途)S7-300PLC传送带工件计数控制程序设计
    Adaptive Mixture Regression Network with Local Counting Map for Crowd Counting
    配色网站收集(持续更新...)
    VUE项目里个性化写个时间轴组件,带折叠效果
    纯CSS画尖角符号
    Docker部署
  • 原文地址:https://www.cnblogs.com/xgbt/p/13191497.html
Copyright © 2011-2022 走看看