各种免费源码共享网站南宁网站开发gxjzdrj
各种免费源码共享网站,南宁网站开发gxjzdrj,涿州网站建设涿州,阳江招聘网最新招聘找工作lc3714式子变形枚举右维护左只含 a、b、c 三种字符的字符串里#xff0c;找出最长的「平衡子串」——要么全同一种、要么两种数量相等、要么三种数量都相等#xff0c;返回最大长度class Solution {
public:int longestBalanced(string s) {int n s.size();int ans 0;// 一…lc3714式子变形枚举右维护左只含 a、b、c 三种字符的字符串里找出最长的「平衡子串」——要么全同一种、要么两种数量相等、要么三种数量都相等返回最大长度class Solution {public:int longestBalanced(string s) {int n s.size();int ans 0;// 一种字母for (int i 0; i n;) {int start i;for (i; i n s[i] s[i - 1]; i);ans max(ans, i - start);}// 两种字母auto f [](char x, char y) - void {for (int i 0; i n; i) {unordered_mapint, int pos {{0, i - 1}}; // 前缀和数组的首项是 0位置相当于在 i-1int d 0; // x 的个数减去 y 的个数for (; i n (s[i] x || s[i] y); i) {d s[i] x ? 1 : -1;if (pos.contains(d)) {ans max(ans, i - pos[d]);} else {pos[d] i;}}}};f(a, b);f(a, c);f(b, c);// 三种字母// 把 (x, y) 压缩成一个 long long方便保存至哈希表// (x, y) 变成 (x n) 32 | (y n)其中 n 避免出现负数unordered_maplong long, int pos {{1LL * n 32 | n, -1}}; // 前缀和数组的首项是 0位置相当于在 -1int cnt[3]{};for (int i 0; i n; i) {cnt[s[i] - a];long long p 1LL * (cnt[0] - cnt[1] n) 32 | (cnt[1] - cnt[2] n);if (pos.contains(p)) {ans max(ans, i - pos[p]);} else {pos[p] i;}}return ans;}};