2026/04/17

[LeetCode] 139 Word Break

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
class Trie {
public:
  static constexpr int NODESIZE = 26;
  bool isWord;
  Trie* node[NODESIZE];

  Trie() {
    isWord = false;
    for (int i = 0; i < NODESIZE; i++)
      this->node[i] = nullptr;
  }
  
  void insert(string word) {
    if (word.empty()) {
      this->isWord = true;
      return;
    }
    int idx = word[0] - 'a';
    if (!this->node[idx])
      this->node[idx] = new Trie();
    this->node[idx]->insert(word.substr(1));
  }
  
  bool search(string word) {
    if (word.empty())
      return this->isWord;
    int idx = word[0] - 'a';
    if (!this->node[idx])
      return false;
    return this->node[idx]->search(word.substr(1));
  }
  
  bool startsWith(string prefix) {
    if (prefix.empty())
      return true;
    int idx = prefix[0] - 'a';
    if (!this->node[idx])
      return false;
    return this->node[idx]->startsWith(prefix.substr(1));
  }
};

class Solution {
public:
  bool wordBreak(string s, vector<string>& wordDict) {
    int SIZE = s.size();
    Trie trie;
    for (string word : wordDict)
      trie.insert(word);
    
    vector<bool> dp(SIZE + 1, false);
    dp[0] = true;
    for (int i = 1; i <= SIZE; i++) 
      for (int j = 1; j <= i; j++) 
        if (dp[j - 1] && trie.search(s.substr(j - 1, i - j + 1)))
          dp[i] = true;

    return dp[SIZE];
  } 
};