| | | 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.ReplaceWords; |
| | | 13 | | |
| | | 14 | | /// <inheritdoc /> |
| | | 15 | | public sealed class ReplaceWordsHashSet : IReplaceWords |
| | | 16 | | { |
| | | 17 | | /// <summary> |
| | | 18 | | /// Time complexity - O(n + m + k * L), where n is the number of words in the dictionary, k is the number of wor |
| | | 19 | | /// the sentence, m is the length of the sentence, and L is the length of the longest word |
| | | 20 | | /// Space complexity - O(n * L + m), where n is the number of words in the dictionary, m is the length of the se |
| | | 21 | | /// and L is the length of the longest word |
| | | 22 | | /// </summary> |
| | | 23 | | /// <param name="dictionary"></param> |
| | | 24 | | /// <param name="sentence"></param> |
| | | 25 | | /// <returns></returns> |
| | | 26 | | public string ReplaceWords(IList<string> dictionary, string sentence) |
| | 6 | 27 | | { |
| | 6 | 28 | | var dictionaryHashSet = new HashSet<string>(dictionary); |
| | | 29 | | |
| | 6 | 30 | | var words = sentence.Split(' '); |
| | | 31 | | |
| | 68 | 32 | | for (var i = 0; i < words.Length; i++) |
| | 28 | 33 | | { |
| | 28 | 34 | | var word = words[i]; |
| | | 35 | | |
| | 140 | 36 | | for (var j = 0; j < word.Length; j++) |
| | 61 | 37 | | { |
| | 61 | 38 | | var prefix = word[..(j + 1)]; |
| | | 39 | | |
| | 61 | 40 | | if (!dictionaryHashSet.Contains(prefix)) |
| | 42 | 41 | | { |
| | 42 | 42 | | continue; |
| | | 43 | | } |
| | | 44 | | |
| | 19 | 45 | | words[i] = prefix; |
| | | 46 | | |
| | 19 | 47 | | break; |
| | | 48 | | } |
| | 28 | 49 | | } |
| | | 50 | | |
| | 6 | 51 | | return string.Join(' ', words); |
| | 6 | 52 | | } |
| | | 53 | | } |