File tree Expand file tree Collapse file tree 1 file changed +36
-0
lines changed Expand file tree Collapse file tree 1 file changed +36
-0
lines changed Original file line number Diff line number Diff line change
1
+ int countPalindromicSubsequence (char * s ){
2
+ int n = strlen (s );
3
+ int i , j ;
4
+ int c , answer ;
5
+ int first [26 ] = {[0 ... 25 ] = -1 };
6
+ int last [26 ] = {[0 ... 25 ] = -1 };
7
+
8
+ // Use two arrays to record the first and last
9
+ // location of each character.
10
+ for (i = 0 ; i < n ; i ++ ) {
11
+ c = s [i ] - 'a' ;
12
+ if (first [c ] == -1 ) {
13
+ first [c ] = i ;
14
+ } else {
15
+ last [c ] = i ;
16
+ }
17
+ }
18
+
19
+ // When a character appears twice, count all the
20
+ // unique character between them.
21
+ answer = 0 ;
22
+ for (i = 0 ; i < 26 ; i ++ ) {
23
+ if (last [i ] != -1 ) {
24
+ int m [26 ] = {[0 ... 25 ] = -1 };
25
+ for (j = first [i ] + 1 ; j < last [i ]; j ++ ) {
26
+ int c = s [j ] - 'a' ;
27
+ if (m [c ] == -1 ) {
28
+ m [c ] = j ;
29
+ answer ++ ;
30
+ }
31
+ }
32
+ }
33
+ }
34
+
35
+ return answer ;
36
+ }
You can’t perform that action at this time.
0 commit comments