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
- 81 lines of C++ from the credited upstream file 3327.cpp.
- The implementation visibly relies on sequence storage.
- 6 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:3 vector<bool> findAnswer(vector<int>& parent, string s) {4 const int n = parent.size();5 vector<bool> ans(n);6 vector<vector<int>> tree(n);7 vector<int> start(n); 8 vector<int> end(n); 9 string dfsStr;10 11 for (int i = 1; i < n; ++i)12 tree[parent[i]].push_back(i);13 14 dfs(tree, 0, 0, s, start, end, dfsStr);15 const string t = join('@' + dfsStr + '$', '#');16 const vector<int> p = manacher(t);17 18 for (int i = 0; i < n; ++i)19 ans[i] = isPalindrome(start[i], end[i], p);20 21 return ans;22 }23 24 private:25 26 int dfs(const vector<vector<int>>& tree, int u, int index, const string& s,27 vector<int>& start, vector<int>& end, string& dfsStr) {28 start[u] = index;29 for (const int v : tree[u])30 index = dfs(tree, v, index, s, start, end, dfsStr);31 end[u] = index;32 dfsStr += s[u];33 return index + 1;34 }35 36 37 38 vector<int> manacher(const string& t) {39 vector<int> p(t.length());40 int center = 0;41 for (int i = 1; i < t.length() - 1; ++i) {42 const int rightBoundary = center + p[center];43 const int mirrorIndex = center - (i - center);44 if (rightBoundary > i)45 p[i] = min(rightBoundary - i, p[mirrorIndex]);46 47 while (t[i + 1 + p[i]] == t[i - 1 - p[i]])48 ++p[i];49 50 51 if (i + p[i] > rightBoundary)52 center = i;53 }54 return p;55 }56 57 58 59 60 61 62 63 64 65 bool isPalindrome(int s, int e, const vector<int>& p) {66 const int length = e - s + 1;67 const int center = s + e + 2;68 return p[center] >= length;69 }70 71 string join(const string& s, char delimiter) {72 string joined;73 for (int i = 0; i < s.length() - 1; ++i) {74 joined += s[i];75 joined += delimiter;76 }77 joined += s.back();78 return joined;79 }80};81