cs: add «567. Permutation in String»

Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2024-10-05 23:35:43 +02:00
parent dd5ec27bb2
commit d2b55bc17b
Signed by: mfocko
SSH key fingerprint: SHA256:icm0fIOSJUpy5+1x23sfr+hLtF9UhY8VpMC7H4WFJP8

View file

@ -0,0 +1,36 @@
public class Solution {
private int[] GetFreqs(string s, int begin, int end) {
var freqs = new int[26];
for (int i = begin; i < end; ++i) {
++freqs[s[i] - 'a'];
}
return freqs;
}
private int[] GetFreqs(string s) => GetFreqs(s, 0, s.Length);
public bool CheckInclusion(string s1, string s2) {
if (s2.Length < s1.Length) {
return false;
}
var expected = GetFreqs(s1);
var running = GetFreqs(s2, 0, s1.Length);
if (Enumerable.SequenceEqual(running, expected)) {
return true;
}
for (int i = s1.Length; i < s2.Length; ++i) {
--running[s2[i - s1.Length] - 'a'];
++running[s2[i] - 'a'];
if (Enumerable.SequenceEqual(running, expected)) {
return true;
}
}
return false;
}
}