Class Solution
-
- All Implemented Interfaces:
public final class Solution3327 - Check if DFS Strings Are Palindromes.
Hard
You are given a tree rooted at node 0, consisting of
nnodes numbered from0ton - 1. The tree is represented by an arrayparentof sizen, whereparent[i]is the parent of nodei. Since node 0 is the root,parent[0] == -1.You are also given a string
sof lengthn, wheres[i]is the character assigned to nodei.Consider an empty string
dfsStr, and define a recursive functiondfs(int x)that takes a nodexas a parameter and performs the following steps in order:Iterate over each child
yofxin increasing order of their numbers , and calldfs(y).Add the character
s[x]to the end of the stringdfsStr.
Note that
dfsStris shared across all recursive calls ofdfs.You need to find a boolean array
answerof sizen, where for each indexifrom0ton - 1, you do the following:Empty the string
dfsStrand calldfs(i).If the resulting string
dfsStris a palindrome , then setanswer[i]totrue. Otherwise, setanswer[i]tofalse.
Return the array
answer.A palindrome is a string that reads the same forward and backward.
Example 1:
Input: parent = -1,0,0,1,1,2, s = "aababa"
Output: true,true,false,true,true,true
Explanation:
Calling
dfs(0)results in the stringdfsStr = "abaaba", which is a palindrome.Calling
dfs(1)results in the stringdfsStr = "aba", which is a palindrome.Calling
dfs(2)results in the stringdfsStr = "ab", which is not a palindrome.Calling
dfs(3)results in the stringdfsStr = "a", which is a palindrome.Calling
dfs(4)results in the stringdfsStr = "b", which is a palindrome.Calling
dfs(5)results in the stringdfsStr = "a", which is a palindrome.
Example 2:
Input: parent = -1,0,0,0,0, s = "aabcb"
Output: true,true,true,true,true
Explanation:
Every call on
dfs(x)results in a palindrome string.Constraints:
n == parent.length == s.length<code>1 <= n <= 10<sup>5</sup></code>
0 <= parent[i] <= n - 1for alli >= 1.parent[0] == -1parentrepresents a valid tree.sconsists only of lowercase English letters.
-
-
Constructor Summary
Constructors Constructor Description Solution()
-
Method Summary
Modifier and Type Method Description final BooleanArrayfindAnswer(IntArray parent, String s)-
-
Method Detail
-
findAnswer
final BooleanArray findAnswer(IntArray parent, String s)
-
-
-
-