| | 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.PermutationInString; |
| | 13 | |
|
| | 14 | | /// <inheritdoc /> |
| | 15 | | public class PermutationInStringSlidingWindowArray : IPermutationInString |
| | 16 | | { |
| | 17 | | private const int ArrayLength = 'z' - 'a' + 1; |
| | 18 | |
|
| | 19 | | /// <summary> |
| | 20 | | /// Time complexity - O(n + m), where n is the length of s1 and m is the length of s2 |
| | 21 | | /// Space complexity - O(1) |
| | 22 | | /// </summary> |
| | 23 | | /// <param name="s1"></param> |
| | 24 | | /// <param name="s2"></param> |
| | 25 | | /// <returns></returns> |
| | 26 | | public bool CheckInclusion(string s1, string s2) |
| 6 | 27 | | { |
| 6 | 28 | | if (s1.Length > s2.Length) |
| 0 | 29 | | { |
| 0 | 30 | | return false; |
| | 31 | | } |
| | 32 | |
|
| 6 | 33 | | var s1Array = new int[ArrayLength]; |
| 6 | 34 | | var s2Array = new int[ArrayLength]; |
| | 35 | |
|
| 46 | 36 | | for (var i = 0; i < s1.Length; i++) |
| 17 | 37 | | { |
| 17 | 38 | | s1Array[s1[i] - 'a']++; |
| 17 | 39 | | s2Array[s2[i] - 'a']++; |
| 17 | 40 | | } |
| | 41 | |
|
| 52 | 42 | | for (var i = 0; i < s2.Length - s1.Length; i++) |
| 21 | 43 | | { |
| 21 | 44 | | if (AreArraysEqual(s1Array, s2Array)) |
| 1 | 45 | | { |
| 1 | 46 | | return true; |
| | 47 | | } |
| | 48 | |
|
| 20 | 49 | | s2Array[s2[i + s1.Length] - 'a']++; |
| 20 | 50 | | s2Array[s2[i] - 'a']--; |
| 20 | 51 | | } |
| | 52 | |
|
| 5 | 53 | | return AreArraysEqual(s1Array, s2Array); |
| 6 | 54 | | } |
| | 55 | |
|
| | 56 | | private static bool AreArraysEqual(int[] array1, int[] array2) |
| 26 | 57 | | { |
| 332 | 58 | | for (var i = 0; i < 26; i++) |
| 163 | 59 | | { |
| 163 | 60 | | if (array1[i] != array2[i]) |
| 23 | 61 | | { |
| 23 | 62 | | return false; |
| | 63 | | } |
| 140 | 64 | | } |
| | 65 | |
|
| 3 | 66 | | return true; |
| 26 | 67 | | } |
| | 68 | | } |