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".

    Analyse: Difine dp[i] is whether S[0...i] can be segmented, thus dp[i] is true means that s[0,...k], s[k + 1, ....i] can be segmented, where 0 < k < i. 

    dp[i] = dp[k] && wordDict.find(s.substr(k + 1, i - k)) != wordDict.end(). 

    Runtime: 16ms.

     1 class Solution {
     2 public:
     3     bool wordBreak(string s, unordered_set<string>& wordDict) {
     4         string newstr = "#" + s;
     5         int len = newstr.size();
     6         vector<bool> dp(len, false);
     7         
     8         dp[0] = true;
     9         for(int i = 1; i < len; i++){
    10             for(int k = 0; k < i; k++){
    11                 dp[i] = dp[k] && wordDict.find(newstr.substr(k + 1, i - k)) != wordDict.end();
    12                 if(dp[i]) break; //s[0...i] can be segmented
    13             }
    14         }
    15         return dp[len - 1];
    16     }
    17 };
  • 相关阅读:
    泛式之争
    测试的本质
    动态语言与静态语言
    对象之间的关系
    关于“重复”的一段交流
    装饰器与子类化
    类的设计质量
    抽象跟难
    Unity经典游戏编程之:球球大作战
    关于Unity 中对UGUI制作任务系统的编程
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/4753438.html
Copyright © 2011-2022 走看看