| | 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.CheckIfOneStringSwapCanMakeStringsEqual; |
| | 13 | |
|
| | 14 | | /// <inheritdoc /> |
| | 15 | | public class CheckIfOneStringSwapCanMakeStringsEqualIterative : ICheckIfOneStringSwapCanMakeStringsEqual |
| | 16 | | { |
| | 17 | | /// <summary> |
| | 18 | | /// Time complexity - O(n) |
| | 19 | | /// Space complexity - O(n) |
| | 20 | | /// </summary> |
| | 21 | | /// <param name="s1"></param> |
| | 22 | | /// <param name="s2"></param> |
| | 23 | | /// <returns></returns> |
| | 24 | | public bool AreAlmostEqual(string s1, string s2) |
| 3 | 25 | | { |
| 3 | 26 | | if (s1.Equals(s2)) |
| 1 | 27 | | { |
| 1 | 28 | | return true; |
| | 29 | | } |
| | 30 | |
|
| 2 | 31 | | var differences = new List<int>(); |
| | 32 | |
|
| 16 | 33 | | for (var i = 0; i < s1.Length; i++) |
| 7 | 34 | | { |
| 7 | 35 | | if (s1[i] != s2[i]) |
| 5 | 36 | | { |
| 5 | 37 | | differences.Add(i); |
| 5 | 38 | | } |
| | 39 | |
|
| 7 | 40 | | if (differences.Count > 2) |
| 1 | 41 | | { |
| 1 | 42 | | return false; |
| | 43 | | } |
| 6 | 44 | | } |
| | 45 | |
|
| 1 | 46 | | return differences.Count == 2 && |
| 1 | 47 | | s1[differences[0]] == s2[differences[1]] && |
| 1 | 48 | | s1[differences[1]] == s2[differences[0]]; |
| 3 | 49 | | } |
| | 50 | | } |