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;
        }
    };
  • 相关阅读:
    多表查询
    mysql记录的增删改和单表查询
    作业45
    修改表 复制表
    多表关联
    约束
    关于服务器raid的一个记录
    安装linux操作系统--浪潮服务器
    关于python中的__new__方法
    关于类的总结之二
  • 原文地址:https://www.cnblogs.com/hejunlin1992/p/7601164.html
Copyright © 2011-2022 走看看