forked from AnasImloul/Leetcode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUnique Length-3 Palindromic Subsequences.java
53 lines (35 loc) · 1.32 KB
/
Unique Length-3 Palindromic Subsequences.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
class Solution {
public int countPalindromicSubsequence(String s) {
int n = s.length();
char[] chArr = s.toCharArray();
int[] firstOcc = new int[26];
int[] lastOcc = new int[26];
Arrays.fill(firstOcc, -1);
Arrays.fill(lastOcc, -1);
for(int i = 0; i < n; i++){
char ch = chArr[i];
if(firstOcc[ch - 'a'] == -1){
firstOcc[ch - 'a'] = i;
}
lastOcc[ch - 'a'] = i;
}
int ans = 0, count = 0;
boolean[] visited;
// check for each character ( start or end of palindrome )
for(int i = 0; i < 26; i++){
int si = firstOcc[i]; // si - starting index
int ei = lastOcc[i]; // ei - ending index
visited = new boolean[26];
count = 0;
// check for unique charcters ( middle of palindrome )
for(int j = si + 1; j < ei; j++){
if(!visited[chArr[j] - 'a']){
visited[chArr[j] - 'a'] = true;
count++;
}
}
ans += count;
}
return ans;
}
}