cs: add «1790. Check if One String Swap Can Make Strings Equal»

URL:	https://leetcode.com/problems/check-if-one-string-swap-can-make-strings-equal/
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2025-02-05 09:34:56 +01:00
parent 1f6394137d
commit e3be56387e
Signed by: mfocko
SSH key fingerprint: SHA256:icm0fIOSJUpy5+1x23sfr+hLtF9UhY8VpMC7H4WFJP8

View file

@ -0,0 +1,33 @@
using Pairing = (char, char);
public class Solution {
private static readonly Pairing UNSET = ('\0', '\0');
private record Diff(int Count, Pairing First, Pairing Second) {
public Diff() : this(0, UNSET, UNSET) { }
public Diff Update(char l, char r) {
if (l == r) {
return this;
}
return new Diff(
Count + 1,
First == UNSET ? (l, r) : First,
First != UNSET && Second == UNSET ? (l, r) : Second
);
}
public bool CanSwap => Count == 0 || (
Count == 2
&& First.Item1 == Second.Item2
&& First.Item2 == Second.Item1
);
}
public bool AreAlmostEqual(string s1, string s2) =>
s1.Zip(s2).Aggregate(new Diff(), (acc, chars) => {
var (l, r) = chars;
return acc.Update(l, r);
}).CanSwap;
}