zoukankan      html  css  js  c++  java
  • leetCoder-wordBreak判断能否分词

    题目

    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.

    分析

    给出一段话,判断能否分词(被dict里的单词分割)

    简单动态规划题,使用dp[i]表示前i个单词能否被分词,则状态转移方程为

    dp[j] = dp[i] && s[i:j]∈dict
    

    如果前i个单词可以被分词,且i-jdict里,则前j个单词可以被分词

    AC代码

    class Solution {
    public:
        bool wordBreak(string s, vector<string>& wordDict) {
            int n = s.length();
            vector<bool> dp(n + 1, false);
            dp[0] = true;
            for(int i=0;i<n;i++){
                for(int j = i; dp[i]&&j<n; j++){
                    auto f = find(wordDict.begin(), wordDict.end(), s.substr(i,j-i+1));
                    if(f != wordDict.end())//找到
                        dp[j+1] = true;
                }
            }
            return dp[n];
        }
    };
    
    转载请保留原文链接及作者
    本文标题:
    文章作者: LepeCoder
    发布时间:
    原始链接:
  • 相关阅读:
    [转]create a basic sql server 2005 trigger to send email alerts
    SDUT OJ 2783 小P寻宝记
    联想杨元庆:互联网不包治百病 概念被夸大
    【Stackoverflow好问题】Java += 操作符实质
    poj 2513 Colored Sticks (trie 树)
    Nginx基础教程PPT
    POJ 1753 Flip Game (DFS + 枚举)
    poj 3020 Antenna Placement (最小路径覆盖)
    Unable to boot : please use a kernel appropriate for your cpu
    HDU 2844 Coins (多重背包)
  • 原文地址:https://www.cnblogs.com/lepeCoder/p/leetCoder-wordBreak.html
Copyright © 2011-2022 走看看