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:
parent
1f6394137d
commit
e3be56387e
1 changed files with 33 additions and 0 deletions
33
cs/check-if-one-string-swap-can-make-strings-equal.cs
Normal file
33
cs/check-if-one-string-swap-can-make-strings-equal.cs
Normal 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;
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue