1. 最长回文子串
function getLongestPalindrome(str) {
let res = "";
for (let i = 0; i < str.length; i++) {
helper(i, i);
helper(i, i + 1);
}
function helper(l, r) {
while (l >= 0 && r < str.length && str[l] === str[r]) {
l--;
r++;
}
const curr_str = str.slice(l + 1, r + 1 - 1);
if (curr_str.length > res.length) res = curr_str;
}
return res;
}
2.已知前序,中序遍历顺序,输出后序遍历顺序
class Node {
constructor(val) {
this.val = val;
this.left = null;
this.right = null;
}
}
class Solution {
constructor() {}
reConstructBinaryTree(pre, tin) {
if (pre.length === 0) {
return null;
}
let root = new Node(pre[0]);
let TinIndex = tin.indexOf(pre[0]);
root.left = this.reConstructBinaryTree(
pre.slice(1, TinIndex + 1),
tin.slice(0, TinIndex)
);
root.right = this.reConstructBinaryTree(
pre.slice(TinIndex + 1),
tin.slice(TinIndex + 1)
);
return root;
}
PostTraversal(root) {
if (root !== null) {
this.PostTraversal(root.left);
this.PostTraversal(root.right);
console.log(root.val);
}
}
}
let pre = ["a", "c", "d", "e", "f", "h", "g", "b"];
let tin = ["d", "e", "c", "a", "h", "f", "b", "g"];
let s = new Solution();
let root = s.reConstructBinaryTree(pre, tin);
s.PostTraversal(root);
#网易雷火2023秋招笔试虐我的瞬间#