Skip to content

Commit

Permalink
Create: 1930-unique-length-3-palindromic
Browse files Browse the repository at this point in the history
  • Loading branch information
Mohammed785 committed Feb 4, 2023
1 parent 49fff18 commit 10fbabe
Show file tree
Hide file tree
Showing 4 changed files with 75 additions and 0 deletions.
13 changes: 13 additions & 0 deletions javascript/1930-unique-length-3-palindromic-subsequences.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
/**
* @param {string} s
* @return {number}
*/
var countPalindromicSubsequence = function (s) {
let count = 0;
let chars = new Set(s);
for(const char of chars){
let first = s.indexOf(char),last = s.lastIndexOf(char);
count += new Set(s.slice(first + 1, last)).size;
}
return count;
};
8 changes: 8 additions & 0 deletions python/1930-unique-length-3-palindromic-subsequences.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
class Solution:
def countPalindromicSubsequence(self, s: str) -> int:
count = 0
chars = set(s)
for char in chars:
first,last = s.find(char),s.rfind(char)
count += len(set(s[first+1:last]))
return count
34 changes: 34 additions & 0 deletions rust/1930-unique-length-3-palindromic-subsequences.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
use std::iter::FromIterator;

impl Solution {
pub fn count_palindromic_subsequence(s: String) -> i32 {
let mut result = 0;
let mut ranges: [(i32, i32); 26] = [(-1, -1); 26];

for (i, c) in s.chars().enumerate() {
let ix = Solution::char_to_index(c) as usize;
if ranges[ix].0 == -1 {
ranges[ix].0 = i as i32;
}
if i as i32 > ranges[ix].1 {
ranges[ix].1 = i as i32;
}
}

for range in ranges {
if range.1 > range.0 {
let mut set: u32 = 0;
for c in s[range.0 as usize + 1..range.1 as usize].chars() {
set |= 1 << Solution::char_to_index(c);
}
result += set.count_ones() as i32;
}
}

result
}

pub fn char_to_index(c: char) -> u32 {
c as u32 - 'a' as u32
}
}
20 changes: 20 additions & 0 deletions typescript/1930-unique-length-3-palindromic-subsequences.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
function countPalindromicSubsequence(s: string): number {
const alphabets = 'abcdefghijklmnopqrstuvwxyz';

const N = alphabets.length;
let count = 0;

for (let i = 0; i < N; i += 1) {
const ch = alphabets[i];
const left = s.indexOf(ch);
const right = s.lastIndexOf(ch);
if (left < right) {
for (const alpha of alphabets) {
const mid = s.indexOf(alpha, left + 1);
if (mid !== -1 && mid < right) count += 1;
}
}
}

return count;
}

0 comments on commit 10fbabe

Please sign in to comment.