You are given a tree (i.e. a connected, undirected graph that has no cycles) rooted at node 0
consisting of n
nodes numbered from 0
to n - 1
. The tree is represented by a 0-indexed array parent
of size n
, where parent[i]
is the parent of node i
. Since node 0
is the root, parent[0] == -1
.
You are also given a string s
of length n
, where s[i]
is the character assigned to node i
.
Return the length of the longest path in the tree such that no pair of adjacent nodes on the path have the same character assigned to them.
Example 1:
Input: parent = [-1,0,0,1,1,2], s = "abacbe" Output: 3 Explanation: The longest path where each two adjacent nodes have different characters in the tree is the path: 0 -> 1 -> 3. The length of this path is 3, so 3 is returned. It can be proven that there is no longer path that satisfies the conditions.
Example 2:
Input: parent = [-1,0,0,0], s = "aabc" Output: 3 Explanation: The longest path where each two adjacent nodes have different characters is the path: 2 -> 0 -> 3. The length of this path is 3, so 3 is returned.
Constraints:
n == parent.length == s.length
1 <= n <= 105
0 <= parent[i] <= n - 1
for alli >= 1
parent[0] == -1
parent
represents a valid tree.s
consists of only lowercase English letters.
相邻字符不同的最长路径。
给你一棵 树(即一个连通、无向、无环图),根节点是节点 0 ,这棵树由编号从 0 到 n - 1 的 n 个节点组成。用下标从 0 开始、长度为 n 的数组 parent 来表示这棵树,其中 parent[i] 是节点 i 的父节点,由于节点 0 是根节点,所以 parent[0] == -1 。
另给你一个字符串 s ,长度也是 n ,其中 s[i] 表示分配给节点 i 的字符。
请你找出路径上任意一对相邻节点都没有分配到相同字符的 最长路径 ,并返回该路径的长度。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/longest-path-with-different-adjacent-characters
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路是 DFS 后序遍历,因为路径不一定穿过根节点。这个思路类似543题和1245题。可以先做一下这两题。
因为题目给的是无向无环图,所以我们需要先把图用一个邻接表建立起来。图建立好之后,我们从节点 0 开始做 DFS 遍历,对于当前节点 root 的所有孩子节点 child,如果 root 指向的 s 中的字母跟 child 指向的一样,则跳过。否则我们就去计算一下每个 child 节点的深度。对于当前节点而言,穿过当前节点的最长路径 = 两个深度最大的子树 + 1。但是我们往当前节点的父节点返回的值是深度最大的子树 + 1。
时间O(n)
空间O(n)
Java实现
1 class Solution { 2 List<Integer>[] g; 3 String s; 4 int res; 5 6 public int longestPath(int[] parent, String s) { 7 this.s = s; 8 int n = parent.length; 9 g = new ArrayList[n]; 10 for (int i = 0; i < n; i++) { 11 g[i] = new ArrayList<>(); 12 } 13 for (int i = 1; i < n; i++) { 14 g[parent[i]].add(i); 15 } 16 dfs(0); 17 return res; 18 } 19 20 private int dfs(int root) { 21 int max1 = 0; 22 int max2 = 0; 23 for (int child : g[root]) { 24 int depth = dfs(child); 25 if (s.charAt(root) == s.charAt(child)) { 26 continue; 27 } 28 if (depth > max1) { 29 max2 = max1; 30 max1 = depth; 31 } else if (depth > max2) { 32 max2 = depth; 33 } 34 } 35 res = Math.max(res, max1 + max2 + 1); 36 return max1 + 1; 37 } 38 }
相关题目
2246. Longest Path With Different Adjacent Characters
标签:Different,parent,int,length,Longest,Characters,child,path,节点 From: https://www.cnblogs.com/cnoodle/p/17051126.html