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

    Runtime: 6ms

     1 class Solution {
     2 public:
     3     bool wordBreak(string s, unordered_set<string>& wordDict) {
     4         if (s.empty()) return true;
     5         
     6         // Have dp[i] indicate whether s[0...i-1] could be broken.
     7         // If there is a dp[j] where j from [0, i - 1] is true, 
     8         // and s[j...i - 1] is in the dictionary, then dp[i] is true
     9         vector<bool> dp(s.size() + 1, false);
    10         dp[0] = true;
    11         for (int i = 1; i <= s.size(); i++) {
    12             for (int j = i; j >= 0; j--) {
    13                 if (dp[j] && wordDict.count(s.substr(j, i - j)) > 0) {
    14                     dp[i] = true;
    15                     break;
    16                 }
    17             }
    18         }
    19         return dp[s.size()];
    20     }
    21 };
  • 相关阅读:
    1059. C语言竞赛(20)
    1057. 数零壹(20)
    1056. 组合数的和(15)
    1054. 求平均值 (20)
    1052. 卖个萌 (20)
    1053. 住房空置率 (20)
    第五周课后作业02(动手动脑)
    课堂动手动脑
    课后作业
    课堂测试动手动脑
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/5844829.html
Copyright © 2020-2023  润新知