Approach
Depth-first search
For Check if DFS Strings Are Palindromes, the implementation follows one branch at a time, making it suitable for components, trees, backtracking, or dependency exploration.
- Define the state carried into one recursive or stack frame.
- Mark or choose the current state before exploring children.
- Combine child results or undo the choice when the branch finishes.
Code notes
- 87 lines of Java from the credited upstream file 3327.java.
- The implementation visibly relies on sequence storage.
- 7 loop blocks detected, together with recursive traversal.
Complexity
Count unique states for graph traversal; for backtracking, count the branching factor and maximum depth.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public boolean[] findAnswer(int[] parent, String s) {3 final int n = parent.length;4 boolean[] ans = new boolean[n];5 List<Integer>[] tree = new List[n];6 7 int[] start = new int[n];8 9 int[] end = new int[n];10 11 for (int i = 0; i < n; ++i)12 tree[i] = new ArrayList<>();13 14 StringBuilder dfsStr = new StringBuilder();15 16 for (int i = 1; i < n; ++i)17 tree[parent[i]].add(i);18 19 dfs(tree, 0, 0, s, start, end, dfsStr);20 final String t = join('@' + dfsStr.toString() + '$', '#');21 final int[] p = manacher(t);22 23 for (int i = 0; i < n; ++i)24 ans[i] = isPalindrome(start[i], end[i], p);25 26 return ans;27 }28 29 30 private int dfs(List<Integer>[] tree, int u, int index, final String s, int[] start, int[] end,31 StringBuilder dfsStr) {32 start[u] = index;33 for (final int v : tree.get(u))34 index = dfs(tree, v, index, s, start, end, dfsStr);35 end[u] = index;36 dfsStr.append(s.charAt(u));37 return index + 1;38 }39 40 41 42 43 44 45 46 47 48 private boolean isPalindrome(int s, int e, int[] p) {49 final int length = e - s + 1;50 final int center = s + e + 2;51 return p[center] >= length;52 }53 54 55 56 private int[] manacher(final String t) {57 int[] p = new int[t.length()];58 int center = 0;59 for (int i = 1; i < t.length() - 1; ++i) {60 int rightBoundary = center + p[center];61 int mirrorIndex = center - (i - center);62 if (rightBoundary > i)63 p[i] = Math.min(rightBoundary - i, p[mirrorIndex]);64 65 while (i + 1 + p[i] < t.length() && i - 1 - p[i] >= 0 &&66 t.charAt(i + 1 + p[i]) == t.charAt(i - 1 - p[i]))67 ++p[i];68 69 70 if (i + p[i] > rightBoundary) {71 center = i;72 }73 }74 return p;75 }76 77 private String join(final String s, char delimiter) {78 StringBuilder joined = new StringBuilder();79 for (int i = 0; i < s.length() - 1; ++i) {80 joined.append(s.charAt(i));81 joined.append(delimiter);82 }83 joined.append(s.charAt(s.length() - 1));84 return joined.toString();85 }86}87