• 139. Word Break


    问题描述:

    Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words.

    Note:

    • The same word in the dictionary may be reused multiple times in the segmentation.
    • You may assume the dictionary does not contain duplicate words.

    Example 1:

    Input: s = "leetcode", wordDict = ["leet", "code"]
    Output: true
    Explanation: Return true because "leetcode" can be segmented as "leet code".
    

    Example 2:

    Input: s = "applepenapple", wordDict = ["apple", "pen"]
    Output: true
    Explanation: Return true because "applepenapple" can be segmented as "apple pen apple".
                 Note that you are allowed to reuse a dictionary word.
    

    Example 3:

    Input: s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"]
    Output: false

    解题思路:

    可以用dp来解。

    对与s的每个位置,可以尝试向前匹配wordDict里面的每个单词。

              int len = (int)w.size();
                    if(i - len > -1 && dp[i-len]){
                        if(s.substr(i-len, len) == w){
                            dp[i] = true;
                            break;
                        }
                    }

    这里先检查了dp[i-len]是否能够匹配成功。

    若能够,则检查这个长度的子串是否存在dict中

    代码:

    class Solution {
    public:
        bool wordBreak(string s, vector<string>& wordDict) {
            int minLen = INT_MAX;
            int n = s.size();
            vector<bool> dp(n+1, false);
            dp[0] = true;
            for(int i = 0; i <= n; i++){
                for(auto w : wordDict){
                    int len = (int)w.size();
                    if(i - len > -1 && dp[i-len]){
                        if(s.substr(i-len, len) == w){
                            dp[i] = true;
                            break;
                        }
                    }
                }
            }
            return dp[n];
        }
    };
  • 相关阅读:
    html5 自定义属性data-*
    企业微信接口授权
    js对象---字符串
    谈谈html5新增的元素及其他功能
    模拟缓存
    jdbc数据库连接
    面向对象的理解
    最简单的Spring+SpringMVC+Mybatis的整合
    EF报错 附加类型model失败
    c# Web服务远程“调用”调试
  • 原文地址:https://www.cnblogs.com/yaoyudadudu/p/9321333.html
Copyright © 2020-2023  润新知