Skip to content

Commit 33ef71d

Browse files
authored
Update 2791-count-paths-that-can-form-a-palindrome-in-a-tree.js
1 parent aa1b47e commit 33ef71d

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

2791-count-paths-that-can-form-a-palindrome-in-a-tree.js

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,44 @@
1+
/**
2+
* @param {number[]} parent
3+
* @param {string} s
4+
* @return {number}
5+
*/
6+
const countPalindromePaths = function (parent, s) {
7+
const n = parent.length
8+
const nxt = Array.from({ length: n }, () => Array())
9+
const cnt = {0:0}
10+
for(let i = 1; i < n; i++) {
11+
nxt[parent[i]].push([i, s[i]])
12+
}
13+
let res = 0
14+
dfs(0, -1, 0)
15+
return res
16+
17+
function dfs(node, parent, state) {
18+
if(cnt[state] != null) res += cnt[state]
19+
for(let i = 0; i < 26; i++) {
20+
const tmp = state ^ (1 << i)
21+
if(cnt[tmp] != null) res += cnt[tmp]
22+
}
23+
if(cnt[state] == null) cnt[state] = 0
24+
cnt[state] += 1
25+
26+
for(const [next, ch] of (nxt[node] || [])) {
27+
if(next === parent) continue
28+
dfs(next, node, state ^ getMask(ch))
29+
}
30+
31+
}
32+
33+
}
34+
function getMask(c) {
35+
const a = 'a'.charCodeAt(0)
36+
return 1 << (c.charCodeAt(0) - a)
37+
}
38+
39+
40+
// another
41+
142
/**
243
* @param {number[]} parent
344
* @param {string} s

0 commit comments

Comments
 (0)