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

    难度中等

     

    给你一个字符串 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
    

    提示:

    • 1 <= s.length <= 300
    • 1 <= wordDict.length <= 1000
    • 1 <= wordDict[i].length <= 20
    • s 和 wordDict[i] 仅有小写英文字母组成
    • wordDict 中的所有字符串 互不相同
    class Solution {
    public:
        bool wordBreak(string s, vector<string>& wordDict) {
    
            vector<bool>dp(s.size()+1,false);
            dp[0] = true;
                for(int j = 1;j <=s.size();j++) {
                    for(int i = 0;i<wordDict.size();i++) {
                        auto word = wordDict[i];
                        int word_len = word.size();
                        if(j-word_len>=0 && s.substr(j-word_len,word_len)==word) {
                            dp[j] = dp[j] || dp[j-word_len];
                        }
                }
            }
            return dp[s.size()];
        }
    };
  • 相关阅读:
    原码, 反码, 补码 详解
    位移运算符
    ASP.NET中httpmodules与httphandlers全解析
    MySQL count
    真正的能理解CSS中的line-height,height与line-height
    IfcEvent
    IfcWorkCalendarTypeEnum
    IfcSingleProjectInstance
    转换模型
    IfcTypeProduct
  • 原文地址:https://www.cnblogs.com/zle1992/p/15522750.html
Copyright © 2011-2022 走看看