zoukankan      html  css  js  c++  java
  • 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];
        }
    };
  • 相关阅读:
    koa2 + webpack 热更新
    koa2在node6中如何运行
    浅拷贝和深拷贝的理解和实现
    angular2多组件通信流程图
    angular2 表单的理解
    ssh-add Could not open a connection to your authentication agent.
    outlook同步异常
    ctrl+c ctrl+d ctrl+z 的区别和使用场景
    grep 详解
    mysql 事务隔离级别 详解
  • 原文地址:https://www.cnblogs.com/yaoyudadudu/p/9321333.html
Copyright © 2011-2022 走看看