/
LongestPathWithDifferentAdjacentCharacters.java
84 lines (70 loc) · 1.97 KB
/
LongestPathWithDifferentAdjacentCharacters.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
// https://leetcode.com/problems/longest-path-with-different-adjacent-characters/
class Solution {
int max = 1;
public int longestPath(int[] parent, String s) {
Map<Integer, List<Integer>> adj = new HashMap<>();
for (int i = 1; i < parent.length; i++) {
adj.computeIfAbsent(parent[i], x -> new ArrayList<>()).add(i);
}
dfs(adj, 0, s);
return max;
}
Path dfs(
Map<Integer, List<Integer>> adj,
int curr,
String s
) {
List<Integer> list = adj.get(curr);
Path p = new Path(1, s.charAt(curr));
if (list == null) {
return p;
}
Path max1 = null, max2 = null;
for (int x: list) {
Path path = dfs(adj, x, s);
if (p.c != path.c) {
if (max1 == null) {
max1 = path;
continue;
}
if (max2 == null) {
if (path.len > max1.len) {
max2 = max1;
max1 = path;
} else {
max2 = path;
}
continue;
}
if (path.len > max1.len) {
max2 = max1;
max1 = path;
} else if (path.len > max2.len) {
max2 = path;
}
}
}
if (max1 == null) {
return p;
}
Path res = Path.copy(p);
res.len += max1.len;
if (max2 == null) {
max = Math.max(max, res.len);
} else {
max = Math.max(max, res.len + max2.len);
}
return res;
}
static class Path {
int len;
char c;
Path(int len, char c) {
this.len = len;
this.c = c;
}
static Path copy(Path other) {
return new Path(other.len, other.c);
}
}
}