
描述 给你一个只由字母’A’和’B’组成的字符串s,找一个最长的子串,要求这个子串里面’A’和’B’的数目相等,输出该子串的长度。
这个子串可以为空。
s的长度n满足 2<=n<=1000000。
示例
样例1
输入: s = "ABAAABBBA"
输出: 8
解释:
子串 s[0,7] 和子串 s[1,8] 满足条件,长度为 8。
样例2
输入: s = "AAAAAA"
输出: 0
解释:
s 中除了空字串,不存在 'A' 和 'B' 数目相等的子串。class Solution {
public:
/**
* @param S: a String consists of a and b
* @return: the longest of the longest string that meets the condition
*/
int getAns(string &s) {
// Write your code here
unordered_map<int,int> m;
m[0] = -1;
int sum = 0, ans = 0;
for(int i = 0; i < s.size(); ++i)
{
if(s[i] =='A')
sum++;
else
sum--;
if(m.find(sum) != m.end())
ans = max(ans, i-m[sum]);
else
m[sum] = i;
}
return ans;
}
};我的CSDN博客地址 https://michael.blog.csdn.net/
长按或扫码关注我的公众号(Michael阿明),一起加油、一起学习进步!