URL: https://leetcode.com/problems/check-if-one-string-swap-can-make-strings-equal/ Signed-off-by: Matej Focko <me@mfocko.xyz>
33 lines
927 B
C#
33 lines
927 B
C#
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;
|
|
}
|