| | 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.BuddyStrings; |
| | 13 | |
|
| | 14 | | /// <inheritdoc /> |
| | 15 | | public class BuddyStringsCounting : IBuddyStrings |
| | 16 | | { |
| | 17 | | /// <summary> |
| | 18 | | /// Time complexity - O(n) |
| | 19 | | /// Space complexity - O(1) |
| | 20 | | /// </summary> |
| | 21 | | /// <param name="s"></param> |
| | 22 | | /// <param name="goal"></param> |
| | 23 | | /// <returns></returns> |
| | 24 | | public bool BuddyStrings(string s, string goal) |
| 5 | 25 | | { |
| 5 | 26 | | if (s.Length != goal.Length || s.Length < 2) |
| 1 | 27 | | { |
| 1 | 28 | | return false; |
| | 29 | | } |
| | 30 | |
|
| 4 | 31 | | if (s == goal) |
| 2 | 32 | | { |
| 2 | 33 | | var duplicates = new bool[26]; |
| | 34 | |
|
| 17 | 35 | | foreach (var index in s.Select(c => c - 'a')) |
| 4 | 36 | | { |
| 4 | 37 | | if (duplicates[index]) |
| 1 | 38 | | { |
| 1 | 39 | | return true; |
| | 40 | | } |
| | 41 | |
|
| 3 | 42 | | duplicates[index] = true; |
| 3 | 43 | | } |
| | 44 | |
|
| 1 | 45 | | return false; |
| | 46 | | } |
| | 47 | |
|
| 2 | 48 | | var firstIndex = -1; |
| 2 | 49 | | var secondIndex = -1; |
| | 50 | |
|
| 18 | 51 | | for (var i = 0; i < s.Length; i++) |
| 7 | 52 | | { |
| 7 | 53 | | if (s[i] == goal[i]) |
| 3 | 54 | | { |
| 3 | 55 | | continue; |
| | 56 | | } |
| | 57 | |
|
| 4 | 58 | | if (firstIndex == -1) |
| 2 | 59 | | { |
| 2 | 60 | | firstIndex = i; |
| 2 | 61 | | } |
| 2 | 62 | | else if (secondIndex == -1) |
| 2 | 63 | | { |
| 2 | 64 | | secondIndex = i; |
| 2 | 65 | | } |
| | 66 | | else |
| 0 | 67 | | { |
| 0 | 68 | | return false; |
| | 69 | | } |
| 4 | 70 | | } |
| | 71 | |
|
| 2 | 72 | | if (secondIndex == -1) |
| 0 | 73 | | { |
| 0 | 74 | | return false; |
| | 75 | | } |
| | 76 | |
|
| 2 | 77 | | return s[firstIndex] == goal[secondIndex] && s[secondIndex] == goal[firstIndex]; |
| 5 | 78 | | } |
| | 79 | | } |