voiddfs(TreeNode *p, string &s){ // 前序遍历拼字符串 if (!p) { s += " #"; return; } s += " " + to_string(p->val); dfs(p->left, s); dfs(p->right, s); }
string ss, st;
intfind(conststring &haystack, conststring &needle){ int h = haystack.length(), n = needle.length(); long M = INT_MAX, B = 256; // INT_MAX是质数! if (h < n) return-1; long highest_power = 1, hh = 0, nh = 0; for (int i = 0; i < n; ++i) { highest_power = (highest_power * B) % M; nh = (nh * B + needle[i]) % M; hh = (hh * B + haystack[i]) % M; } for (int i = 0; i < h - n + 1; ++i) { if (i >= 1) { hh = (hh * B + M - haystack[i - 1] * highest_power % M + haystack[i + n - 1]) % M; // 这里highest_power是B的n次方,因为先整体左移再减高位,如果先减高位再整体左移就是n-1次方了 } if (hh == nh && haystack.substr(i, n) == needle) { return i; } } return-1; } };