| | 1 | | // -------------------------------------------------------------------------------- |
| | 2 | | // Copyright (C) 2025 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.RansomNote; |
| | 13 | |
|
| | 14 | | /// <inheritdoc /> |
| | 15 | | public class RansomNoteDictionary : IRansomNote |
| | 16 | | { |
| | 17 | | /// <summary> |
| | 18 | | /// Time complexity - O(m + n) |
| | 19 | | /// Space complexity - O(n) |
| | 20 | | /// </summary> |
| | 21 | | /// <param name="ransomNote"></param> |
| | 22 | | /// <param name="magazine"></param> |
| | 23 | | /// <returns></returns> |
| | 24 | | public bool CanConstruct(string ransomNote, string magazine) |
| 3 | 25 | | { |
| 3 | 26 | | var magazineDictionary = new Dictionary<char, int>(); |
| | 27 | |
|
| 17 | 28 | | foreach (var magazineChar in magazine.Where(magazineChar => !magazineDictionary.TryAdd(magazineChar, 1))) |
| 1 | 29 | | { |
| 1 | 30 | | magazineDictionary[magazineChar]++; |
| 1 | 31 | | } |
| | 32 | |
|
| 17 | 33 | | foreach (var ransomNoteChar in ransomNote) |
| 5 | 34 | | { |
| 5 | 35 | | if (magazineDictionary.TryGetValue(ransomNoteChar, out var magazineCharValue)) |
| 4 | 36 | | { |
| 4 | 37 | | if (magazineCharValue > 0) |
| 3 | 38 | | { |
| 3 | 39 | | magazineDictionary[ransomNoteChar]--; |
| 3 | 40 | | } |
| | 41 | | else |
| 1 | 42 | | { |
| 1 | 43 | | return false; |
| | 44 | | } |
| 3 | 45 | | } |
| | 46 | | else |
| 1 | 47 | | { |
| 1 | 48 | | return false; |
| | 49 | | } |
| 3 | 50 | | } |
| | 51 | |
|
| 1 | 52 | | return true; |
| 3 | 53 | | } |
| | 54 | | } |