Aristides
Senior Member
Hôm nay đổi gió sang C#, nghe đồn thằng này lai giữa Java và C++
Edit: thấy bài nay có tag Trie mà nhiều người chơi luôn set
C#:
public class Solution {
public bool WordBreak(string s, IList<string> wordDict) {
Trie t = new Trie();
for(int i = 0; i < wordDict.Count; i++){
t.InsertWord(wordDict[i]);
}
bool[] dp = new bool[s.Length + 1];
dp[0] = true;
for(int i = 1; i <= s.Length; i++){
for(int j = 0; j < i; j++){
if(dp[j] == true && t.ContainsWord(s.Substring(j, i - j)) == true){
dp[i] = true;
}
}
}
return dp[s.Length];
}
}
class Node {
private Node[] child;
private bool isEnd;
public Node(){
child = new Node[26];
isEnd = false;
}
public bool IsEnd(){
return isEnd;
}
public void SetEnd(bool val){
isEnd = val;
}
public bool ContainsChar(char c){
return child[c - 'a'] != null;
}
public Node GetChild(char c){
return child[c - 'a'];
}
public void AddChar(char c){
child[c - 'a'] = new Node();
}
}
class Trie {
private Node root;
public Trie(){
root = new Node();
}
public void InsertWord(string word){
Node ptr = root;
for(int i = 0; i < word.Length; i++){
char curr = word[i];
if(!ptr.ContainsChar(curr)){
ptr.AddChar(curr);
}
ptr = ptr.GetChild(curr);
}
ptr.SetEnd(true);
}
public bool ContainsWord(string word){
Node ptr = root;
for(int i = 0; i < word.Length; i++){
char curr = word[i];
if(ptr.ContainsChar(curr)){
ptr = ptr.GetChild(curr);
}
else{
return false;
}
}
return ptr.IsEnd();
}
}



