Skip to content

Commit 1813b99

Browse files
committed
Runtime: 26 ms (Top 93.60%) | Memory: 51.8 MB (Top 51.74%)
1 parent c3d74fc commit 1813b99

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
// Runtime: 26 ms (Top 93.60%) | Memory: 51.8 MB (Top 51.74%)
2+
class Solution {
3+
public int countPalindromicSubsequence(String s) {
4+
5+
int n = s.length();
6+
7+
char[] chArr = s.toCharArray();
8+
9+
int[] firstOcc = new int[26];
10+
int[] lastOcc = new int[26];
11+
12+
Arrays.fill(firstOcc, -1);
13+
Arrays.fill(lastOcc, -1);
14+
15+
for(int i = 0; i < n; i++){
16+
17+
char ch = chArr[i];
18+
19+
if(firstOcc[ch - 'a'] == -1){
20+
firstOcc[ch - 'a'] = i;
21+
}
22+
23+
lastOcc[ch - 'a'] = i;
24+
}
25+
26+
int ans = 0, count = 0;
27+
28+
boolean[] visited;
29+
30+
// check for each character ( start or end of palindrome )
31+
for(int i = 0; i < 26; i++){
32+
33+
int si = firstOcc[i]; // si - starting index
34+
int ei = lastOcc[i]; // ei - ending index
35+
36+
visited = new boolean[26];
37+
38+
count = 0;
39+
40+
// check for unique charcters ( middle of palindrome )
41+
for(int j = si + 1; j < ei; j++){
42+
43+
if(!visited[chArr[j] - 'a']){
44+
visited[chArr[j] - 'a'] = true;
45+
count++;
46+
}
47+
}
48+
49+
ans += count;
50+
}
51+
52+
return ans;
53+
}
54+
}

0 commit comments

Comments
 (0)