vector<vector<int> > f; TreeAncestor(int n, vector<int>& parent) { f = vector<vector<int> >(n, vector<int>(N, -1)); for (int i = 0; i < n; i++) { f[i][0] = parent[i]; // 2 ^ 0 == 1; } for (int j = 1; j < N; j++) { for (int i = 0; i < n; i++) { if (f[i][j-1] != -1) { f[i][j] = f[f[i][j-1]][j-1]; } } } }
intgetKthAncestor(int node, int k){
for (int i = 0; i < N; i++) { if ((k >> i) & 1) { node = f[node][i]; } if (node == -1) return-1; } return node; } };
/** * Your TreeAncestor object will be instantiated and called as such: * TreeAncestor* obj = new TreeAncestor(n, parent); * int param_1 = obj->getKthAncestor(node,k); */
classSolution { public: intlengthOfLongestSubstring(string s){ int l = 0; map<char, int> a; for (int i = 0; i < s.size(); i++) a[s[i]] = -1; int ans = 0; // 这题等核心:顺序,更新l的顺序,l每次选可能的最大值 for (int i = 0; i < s.size(); i++) { if (a[s[i]] != - 1) l = max(a[s[i]] + 1, l); ans = max(i - l + 1, ans); a[s[i]] = i; } ans = max(ans, int(s.size()- l)); return ans; } };