| | 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.WordPattern; |
| | 13 | |
|
| | 14 | | /// <inheritdoc /> |
| | 15 | | public class WordPatternDictionary : IWordPattern |
| | 16 | | { |
| | 17 | | /// <summary> |
| | 18 | | /// Time complexity - O(m^2), where m is the length of pattern |
| | 19 | | /// Space complexity - O(m), where m is the length of pattern |
| | 20 | | /// </summary> |
| | 21 | | /// <param name="pattern"></param> |
| | 22 | | /// <param name="s"></param> |
| | 23 | | /// <returns></returns> |
| | 24 | | public bool WordPattern(string pattern, string s) |
| 5 | 25 | | { |
| 5 | 26 | | var patternHashSet = new Dictionary<char, string>(); |
| | 27 | |
|
| 5 | 28 | | var sArray = s.Split(' '); |
| | 29 | |
|
| 5 | 30 | | if (pattern.Length != sArray.Length) |
| 1 | 31 | | { |
| 1 | 32 | | return false; |
| | 33 | | } |
| | 34 | |
|
| 26 | 35 | | for (var i = 0; i < pattern.Length; i++) |
| 12 | 36 | | { |
| 12 | 37 | | if (patternHashSet.TryGetValue(pattern[i], out var value)) |
| 5 | 38 | | { |
| 5 | 39 | | if (value != sArray[i]) |
| 2 | 40 | | { |
| 2 | 41 | | return false; |
| | 42 | | } |
| 3 | 43 | | } |
| | 44 | | else |
| 7 | 45 | | { |
| 7 | 46 | | if (patternHashSet.ContainsValue(sArray[i])) |
| 1 | 47 | | { |
| 1 | 48 | | return false; |
| | 49 | | } |
| | 50 | |
|
| 6 | 51 | | patternHashSet.Add(pattern[i], sArray[i]); |
| 6 | 52 | | } |
| 9 | 53 | | } |
| | 54 | |
|
| 1 | 55 | | return true; |
| 5 | 56 | | } |
| | 57 | | } |