LeetCode/cs/permutation-in-string.cs

37 lines
898 B
C#
Raw Normal View History

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;
}
}