Question

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

Solution

用动态规划求解,遍历所有长度,看当前长度i是否可以完全分化。 长度为i的字符串分为两部分,前一部分是已经算过的是否可以划分的,只需要在字典中找后面一部分是否存在。

时间复杂度为O(n^2),空间复杂度为O(n).

Code

class Solution {
public:
    bool wordBreak(string s, unordered_set<string> &dict) {
        vector<bool> dp(s.length() + 1, false);
        dp[0] = true;
        
        for (int i = 1; i <= s.length(); i++) {
            for (int j = 0; j <= i; j++) {
                if (dp[j]) {
                    string str = s.substr(j, i - j);
                    if (dict.find(str) != dict.end()) {
                        dp[i] = true;
                        break;
                    }
                }
            }
        }
        return dp[s.length()];
    }
};

相关文章:

  • 2022-12-23
  • 2021-06-16
  • 2022-12-23
猜你喜欢
  • 2021-10-16
  • 2022-02-09
  • 2021-06-16
  • 2021-09-23
  • 2021-12-05
  • 2022-03-03
  • 2021-10-18
相关资源
相似解决方案