zoukankan      html  css  js  c++  java
  • LeetCode——Word Break

    LeetCode——Word Break

    Question

    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. You may assume the dictionary does not contain duplicate words.

    For example, given
    s = "leetcode",
    dict = ["leet", "code"].

    Return true because "leetcode" can be segmented as "leet code".

    Solution

    动态规划的思想,从头开始扫描字符串,判断当前子字符串是否可以在字典中查找到,取决于自身以及对这个子字符串的所有划分方式是否可以查找到。
    递推关系式子: dp[i] = dp[j] && dp[i - j] (0 <= j <= i)
    初始值 dp[0] = true; 表示子字符串长度为0的时候,是可以查找到的。

    Answer

    public:
        bool wordBreak(string s, vector<string>& wordDict) {
            if (wordDict.size() == 0 || s.empty())
                return false;
            vector<int> dp(s.length() + 1, false);
            dp[0] = true;
            for (int i = 1; i <= s.length(); i++) {
                for (int j = 0; j <= i; j++) {
                    if (dp[j]) {
                    	// 第二个参数表示,表示从j开始的字符个数
                        string str1 = s.substr((unsigned int)j, i - j);
                        if (check(wordDict, str1)) {
                            dp[i] = true;
                            break;
                        }
                    }
                }
            }
            return dp[s.length()];
        }
        bool check(vector<string>& wordDict, string& str1) {
            for (string str : wordDict)
                if (str == str1)
                    return true;
            return false;
        }
    };
    
  • 相关阅读:
    ubuntu系统安装微信小程序开发工具
    【工具】vscode-代码编辑器详解
    微信小程序开发
    webpack基本配置
    vue相关知识
    史上最强vue总结~万字长文---面试开发全靠它了
    ES6——字符串
    ES6——Proxy与Reflect
    ES6——Map与Set
    ES6——Symbol
  • 原文地址:https://www.cnblogs.com/zhonghuasong/p/6957705.html
Copyright © 2011-2022 走看看