From 5d40a9cbd4e4241784d8e1b9ce17a9888a1d5845 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Mon, 23 Sep 2024 23:11:04 +0200 Subject: [PATCH] =?UTF-8?q?cs:=20add=20=C2=AB2707.=20Extra=20Characters=20?= =?UTF-8?q?in=20a=20String=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Matej Focko --- cs/extra-characters-in-a-string.cs | 50 ++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 cs/extra-characters-in-a-string.cs diff --git a/cs/extra-characters-in-a-string.cs b/cs/extra-characters-in-a-string.cs new file mode 100644 index 0000000..e07702d --- /dev/null +++ b/cs/extra-characters-in-a-string.cs @@ -0,0 +1,50 @@ +public class Solution { + private class Node { + public Dictionary Next { get; set; } = new(); + public bool Has { get; set; } = false; + + public Node() { } + } + + private static Node MakeTrie(string[] dictionary) { + var root = new Node(); + + foreach (var word in dictionary) { + var node = root; + foreach (var c in word) { + if (!node.Next.ContainsKey(c)) { + node.Next[c] = new(); + } + node = node.Next[c]; + } + node.Has = true; + } + + return root; + } + + public int MinExtraChar(string s, string[] dictionary) { + var trie = MakeTrie(dictionary); + + var length = s.Length; + var dp = new int[length + 1]; + + for (var start = length - 1; start >= 0; --start) { + dp[start] = 1 + dp[start + 1]; + + var node = trie; + for (var end = start; end < length; ++end) { + if (!node.Next.ContainsKey(s[end])) { + break; + } + + node = node.Next[s[end]]; + if (node.Has) { + dp[start] = Math.Min(dp[start], dp[end + 1]); + } + } + } + + return dp[0]; + } +}