cs: add «1930. Unique Length-3 Palindromic Subsequences»
URL: https://leetcode.com/problems/unique-length-3-palindromic-subsequences/ Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
parent
5c88e2bfe0
commit
eb0e5a5391
1 changed files with 31 additions and 0 deletions
31
cs/unique-length-3-palindromic-subsequences.cs
Normal file
31
cs/unique-length-3-palindromic-subsequences.cs
Normal file
|
@ -0,0 +1,31 @@
|
|||
public class Solution {
|
||||
private static readonly int NOT_FOUND = int.MaxValue;
|
||||
|
||||
public int CountPalindromicSubsequence(string s) {
|
||||
var (first, last) = (new int[26], new int[26]);
|
||||
Array.Fill(first, NOT_FOUND);
|
||||
|
||||
// Initialize the indices
|
||||
for (var i = 0; i < s.Length; ++i) {
|
||||
var idx = s[i] - 'a';
|
||||
first[idx] = Math.Min(first[idx], i);
|
||||
last[idx] = i;
|
||||
}
|
||||
|
||||
var count = 0;
|
||||
for (var c = 0; c < 26; ++c) {
|
||||
if (first[c] == NOT_FOUND) {
|
||||
continue;
|
||||
}
|
||||
|
||||
var between = new HashSet<char>();
|
||||
for (int i = first[c] + 1; i < last[c]; ++i) {
|
||||
between.Add(s[i]);
|
||||
}
|
||||
|
||||
count += between.Count;
|
||||
}
|
||||
|
||||
return count;
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue