| | | 1 | | // -------------------------------------------------------------------------------- |
| | | 2 | | // Copyright (C) 2026 Eugene Eremeev (also known as Yevhenii Yeriemeieiv). |
| | | 3 | | // All Rights Reserved. |
| | | 4 | | // -------------------------------------------------------------------------------- |
| | | 5 | | // This software is the confidential and proprietary information of Eugene Eremeev |
| | | 6 | | // (also known as Yevhenii Yeriemeieiv) ("Confidential Information"). You shall not |
| | | 7 | | // disclose such Confidential Information and shall use it only in accordance with |
| | | 8 | | // the terms of the license agreement you entered into with Eugene Eremeev (also |
| | | 9 | | // known as Yevhenii Yeriemeieiv). |
| | | 10 | | // -------------------------------------------------------------------------------- |
| | | 11 | | |
| | | 12 | | namespace LeetCode.Algorithms.ExtraCharactersInString; |
| | | 13 | | |
| | | 14 | | /// <inheritdoc /> |
| | | 15 | | public sealed class ExtraCharactersInStringDynamicProgrammingHashSet : IExtraCharactersInString |
| | | 16 | | { |
| | | 17 | | /// <summary> |
| | | 18 | | /// Time complexity - O(n^3), n is the length of the longest word in the dictionary |
| | | 19 | | /// Space complexity - O(n + m), m is the number of words in the dictionary and n is the length of the longest w |
| | | 20 | | /// the dictionary |
| | | 21 | | /// </summary> |
| | | 22 | | /// <param name="s"></param> |
| | | 23 | | /// <param name="dictionary"></param> |
| | | 24 | | /// <returns></returns> |
| | | 25 | | public int MinExtraChar(string s, string[] dictionary) |
| | 6 | 26 | | { |
| | 6 | 27 | | var dp = new int[s.Length + 1]; |
| | | 28 | | |
| | 6 | 29 | | Array.Fill(dp, int.MaxValue); |
| | | 30 | | |
| | 6 | 31 | | dp[0] = 0; |
| | | 32 | | |
| | 6 | 33 | | var wordsHashSet = new HashSet<string>(dictionary); |
| | | 34 | | |
| | 226 | 35 | | for (var i = 1; i < dp.Length; i++) |
| | 107 | 36 | | { |
| | 107 | 37 | | dp[i] = dp[i - 1] + 1; |
| | | 38 | | |
| | 3296 | 39 | | for (var j = 0; j < i; j++) |
| | 1541 | 40 | | { |
| | 1541 | 41 | | var word = s.Substring(j, i - j); |
| | | 42 | | |
| | 1541 | 43 | | if (wordsHashSet.Contains(word)) |
| | 30 | 44 | | { |
| | 30 | 45 | | dp[i] = Math.Min(dp[i], dp[j]); |
| | 30 | 46 | | } |
| | 1541 | 47 | | } |
| | 107 | 48 | | } |
| | | 49 | | |
| | 6 | 50 | | return dp[^1]; |
| | 6 | 51 | | } |
| | | 52 | | } |