zoukankan      html  css  js  c++  java
  • [Leetcode] 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. 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".

    UPDATE (2017/1/4):
    The wordDict parameter had been changed to a list of strings (instead of a set of strings). Please reload the code definition to get the latest changes.

      题目大意:给定字符串s与字典dict,判断字符串s能否由字典中的元素组成。

      分析:使用动态规划法。dp[i]=true表示字符串中0到i-1部分的子字符串能由字典中字符串组成。

    class Solution {
    public:
        bool wordBreak(string s, vector<string>& wordDict) {
            int n=s.size();
            vector<bool> dp(n+1, false);
            dp[0]=true;
            for(int i=1;i<=n;i++)
            {
                for(int j=i-1;j>=0;j--)
                {
                    if(dp[j])
                    {
                        string sub = s.substr(j,i-j);
                        if(findWord(sub, wordDict))
                        {
                            dp[i]=true;
                            break;
                        }     
                    }
                }
                
            }
            return dp[n];
        }
        bool findWord(string s, vector<string>& wordDict)
        {
            for(int i=0;i<wordDict.size();i++)
            {
                if(s==wordDict[i]) return true;
            }
            return false;
        }
    };
  • 相关阅读:
    Libevent源码分析系列
    TCP检验和
    Redis—数据结构之list
    STL—list
    STL—vector
    STL—vector空间的动态增长
    STL—内存的配置与释放
    Actuator 未授权访问之heapdump利用
    Git submodule update 命令执行
    利用Haproxy搭建 HTTP 请求走私(Request smuggling)环境
  • 原文地址:https://www.cnblogs.com/hejunlin1992/p/7601164.html
Copyright © 2011-2022 走看看