[InterviewBit] Word Break

Word Break

  • Time :
  • Space :
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
struct Trie {
Trie* next[26];
bool eof;
Trie(): eof(false) {
memset(next, 0, sizeof next);
}

void insert(string s, int p = 0) {
if(p == s.length()) eof = true;
else {
if(!next[s[p]-'a']) next[s[p]-'a'] = new Trie();
next[s[p]-'a']->insert(s,p+1);
}
}
};

int helper(Trie* root, string s, int p = 0) {
if(p == s.length()) return true;
Trie* runner = root;
for(int i = p; i < s.length(); i++) {
if(!runner->next[s[i]-'a']) return false;
runner = runner->next[s[i]-'a'];
if(runner->eof) {
if(helper(root, s, i + 1)) return true;
}
}
return false;
}

int Solution::wordBreak(string A, vector<string> &B) {
Trie* t = new Trie();
for(auto& b : B) t->insert(b);
return helper(t,A);
}
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/09/13/PS/interviewbit/word-break/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.