File tree Expand file tree Collapse file tree
javascript/LeetCode/String Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ /**
2+ * 1930. Unique Length-3 Palindromic Subsequences
3+ *
4+ * 回傳屬於s迴文的子字串
5+ *
6+ * @param {string } s
7+ * @return {number }
8+ */
9+ var countPalindromicSubsequence = function ( s ) {
10+ // 只能有3個字母,第一個字母和最後一個字母是一樣的,唯獨中間字母不同 = 迴文
11+ // 會有一個字母出現至少2次
12+
13+ // solution 1.
14+ // let ans = 0;
15+ // let set = new Set(s);
16+ // for(const char of set) {
17+ // let start = s.indexOf(char);
18+ // let end = s.lastIndexOf(char);
19+
20+ // if(start < end){
21+ // ans += new Set(s.slice(start + 1, end)).size;
22+ // }
23+ // }
24+ // return ans;
25+
26+ // solution 2.
27+ let map = new Map ( ) ;
28+ let ans = 0 ;
29+ for ( let i = 0 ; i < s . length ; ++ i ) {
30+ if ( ! map . has ( s [ i ] ) ) {
31+ map . set ( s [ i ] , [ ] ) ;
32+ }
33+ map . get ( s [ i ] ) . push ( i ) ;
34+ }
35+ console . log ( map )
36+ for ( const [ char , index ] of map ) {
37+ const start = index [ 0 ] ;
38+ const end = index [ index . length - 1 ] ;
39+ if ( end - start <= 1 ) {
40+ continue ;
41+ }
42+
43+ const set = new Set ( ) ;
44+ for ( let i = start + 1 ; i < end ; i ++ ) {
45+ set . add ( s [ i ] ) ;
46+ }
47+ ans += set . size ;
48+ }
49+ return ans ;
50+ } ;
51+ // let s = "aabca";
52+ /**
53+ * 3
54+ * The 3 palindromic subsequences of length 3 are:
55+ * "aba" (subsequence of "aabca")
56+ * "aaa" (subsequence of "aabca")
57+ * "aca" (subsequence of "aabca")
58+ */
59+ // let s = "uuuuu";
60+ // 1
61+ let s = "ckafnafqo"
62+ // 4
63+ console . log ( countPalindromicSubsequence ( s ) ) ;
You can’t perform that action at this time.
0 commit comments