Skip to content

Commit 10fbabe

Browse files
committed
Create: 1930-unique-length-3-palindromic
1 parent 49fff18 commit 10fbabe

4 files changed

+75
-0
lines changed
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
/**
2+
* @param {string} s
3+
* @return {number}
4+
*/
5+
var countPalindromicSubsequence = function (s) {
6+
let count = 0;
7+
let chars = new Set(s);
8+
for(const char of chars){
9+
let first = s.indexOf(char),last = s.lastIndexOf(char);
10+
count += new Set(s.slice(first + 1, last)).size;
11+
}
12+
return count;
13+
};
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
class Solution:
2+
def countPalindromicSubsequence(self, s: str) -> int:
3+
count = 0
4+
chars = set(s)
5+
for char in chars:
6+
first,last = s.find(char),s.rfind(char)
7+
count += len(set(s[first+1:last]))
8+
return count
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
use std::iter::FromIterator;
2+
3+
impl Solution {
4+
pub fn count_palindromic_subsequence(s: String) -> i32 {
5+
let mut result = 0;
6+
let mut ranges: [(i32, i32); 26] = [(-1, -1); 26];
7+
8+
for (i, c) in s.chars().enumerate() {
9+
let ix = Solution::char_to_index(c) as usize;
10+
if ranges[ix].0 == -1 {
11+
ranges[ix].0 = i as i32;
12+
}
13+
if i as i32 > ranges[ix].1 {
14+
ranges[ix].1 = i as i32;
15+
}
16+
}
17+
18+
for range in ranges {
19+
if range.1 > range.0 {
20+
let mut set: u32 = 0;
21+
for c in s[range.0 as usize + 1..range.1 as usize].chars() {
22+
set |= 1 << Solution::char_to_index(c);
23+
}
24+
result += set.count_ones() as i32;
25+
}
26+
}
27+
28+
result
29+
}
30+
31+
pub fn char_to_index(c: char) -> u32 {
32+
c as u32 - 'a' as u32
33+
}
34+
}
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
function countPalindromicSubsequence(s: string): number {
2+
const alphabets = 'abcdefghijklmnopqrstuvwxyz';
3+
4+
const N = alphabets.length;
5+
let count = 0;
6+
7+
for (let i = 0; i < N; i += 1) {
8+
const ch = alphabets[i];
9+
const left = s.indexOf(ch);
10+
const right = s.lastIndexOf(ch);
11+
if (left < right) {
12+
for (const alpha of alphabets) {
13+
const mid = s.indexOf(alpha, left + 1);
14+
if (mid !== -1 && mid < right) count += 1;
15+
}
16+
}
17+
}
18+
19+
return count;
20+
}

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy