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;
        }
    };
  • 相关阅读:
    php基本语法
    php的环境搭建
    Java数组及其内存分配
    最快的maven镜像
    配置maven到运行
    配置maven
    maven的eclise配置
    mysql中bit_count和bit_or函数的含义
    怎样查看MySQL是否区分大小写
    linux忘记mysql密码找回方法
  • 原文地址:https://www.cnblogs.com/hejunlin1992/p/7601164.html
Copyright © 2011-2022 走看看