File tree Expand file tree Collapse file tree 3 files changed +63
-2
lines changed
solution/2200-2299/2246.Longest Path With Different Adjacent Characters Expand file tree Collapse file tree 3 files changed +63
-2
lines changed Original file line number Diff line number Diff line change 73
73
### ** TypeScript**
74
74
75
75
``` ts
76
-
76
+ function longestPath(parent : number [], s : string ): number {
77
+ const n = parent .length ;
78
+ let graph = Array .from ({ length: n }, v => []);
79
+ for (let i = 1 ; i < n ; i ++ ) {
80
+ graph [parent [i ]].push (i );
81
+ }
82
+ let ans = 0 ;
83
+ function dfs (x : number ): number {
84
+ let maxLen = 0 ;
85
+ for (let y of graph [x ]) {
86
+ let len = dfs (y ) + 1 ;
87
+ if (s .charAt (x ) !== s .charAt (y )) {
88
+ ans = Math .max (maxLen + len , ans );
89
+ maxLen = Math .max (len , maxLen );
90
+ }
91
+ }
92
+ return maxLen ;
93
+ }
94
+ dfs (0 );
95
+ return ans + 1 ;
96
+ };
77
97
```
78
98
79
99
### ** ...**
Original file line number Diff line number Diff line change @@ -59,7 +59,27 @@ It can be proven that there is no longer path that satisfies the conditions.
59
59
### ** TypeScript**
60
60
61
61
``` ts
62
-
62
+ function longestPath(parent : number [], s : string ): number {
63
+ const n = parent .length ;
64
+ let graph = Array .from ({ length: n }, v => []);
65
+ for (let i = 1 ; i < n ; i ++ ) {
66
+ graph [parent [i ]].push (i );
67
+ }
68
+ let ans = 0 ;
69
+ function dfs (x : number ): number {
70
+ let maxLen = 0 ;
71
+ for (let y of graph [x ]) {
72
+ let len = dfs (y ) + 1 ;
73
+ if (s .charAt (x ) !== s .charAt (y )) {
74
+ ans = Math .max (maxLen + len , ans );
75
+ maxLen = Math .max (len , maxLen );
76
+ }
77
+ }
78
+ return maxLen ;
79
+ }
80
+ dfs (0 );
81
+ return ans + 1 ;
82
+ };
63
83
```
64
84
65
85
### ** ...**
Original file line number Diff line number Diff line change
1
+ function longestPath ( parent : number [ ] , s : string ) : number {
2
+ const n = parent . length ;
3
+ let graph = Array . from ( { length : n } , v => [ ] ) ;
4
+ for ( let i = 1 ; i < n ; i ++ ) {
5
+ graph [ parent [ i ] ] . push ( i ) ;
6
+ }
7
+ let ans = 0 ;
8
+ function dfs ( x : number ) : number {
9
+ let maxLen = 0 ;
10
+ for ( let y of graph [ x ] ) {
11
+ let len = dfs ( y ) + 1 ;
12
+ if ( s . charAt ( x ) !== s . charAt ( y ) ) {
13
+ ans = Math . max ( maxLen + len , ans ) ;
14
+ maxLen = Math . max ( len , maxLen ) ;
15
+ }
16
+ }
17
+ return maxLen ;
18
+ }
19
+ dfs ( 0 ) ;
20
+ return ans + 1 ;
21
+ } ;
You can’t perform that action at this time.
0 commit comments