zoukankan      html  css  js  c++  java
  • Word Break

    Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separated sequence of one or more dictionary words.

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

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

    利用动态规划算法,创建一个vector记录0-i的字符串是否可以由字典中的词组成,若可以则继续判断剩下的是否可以由字典词组成。为防止s的一部分可以分割而另一部分不可分割,需全部遍历一遍s,而不能根据i跳跃遍历。

     1 class Solution {
     2 public:
     3     bool wordBreak(string s, unordered_set<string>& wordDict) {
     4         int n=s.length();
     5         if(n<1) return true;
     6         if(wordDict.empty()) return false;
     7         vector<bool> dp(n+1,false);
     8         dp[0]=true;
     9         for(int i=0;i<n;i++)
    10         {
    11             if(dp[i])
    12             {
    13                 for(int j=i;j<n;j++)
    14                 {
    15                     string tmps=s.substr(i,j-i+1);
    16                     if(wordDict.count(tmps))
    17                         dp[j+1]=true;
    18                 }
    19             }
    20         }
    21         return dp[n];
    22     }
    23 };
  • 相关阅读:
    Mac上如何用命令行修改proxy设置
    Mac上解决访问github慢问题
    Bootstrap布局
    ListView详解
    sql server命名规范
    表的管理与操作
    常用编程技巧和方法
    有联系的jQuery选择器
    sql基础查询语句
    数值特征
  • 原文地址:https://www.cnblogs.com/zl1991/p/4692096.html
Copyright © 2011-2022 走看看