题目
https://www.lintcode.com/problem/1443
给你一个只由字母'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' 数目相等的子串。
思路
注意:鉴于n长度可能很大,为1000000,因此2层for双指针不太可行,会超时
hashmap用来存储, A出现的个数和对应的起始位置.
for循环, 如果当前是A, count++. 是B, count--.
在for循环的过程中, 只要存在hashmap曾经出现过的A的个数,
就更新ans为max(ans, i - map.get(count)).
答案
public class Solution {
/**
* @param s: a String consists of a and b
* @return: the longest of the longest string that meets the condition
*/
public int getAns(String s) {
/*
注意:鉴于n长度可能很大,为1000000,因此2层for双指针不太可行,会超时
hashmap用来存储, A出现的个数和对应的起始位置.
for循环, 如果当前是A, count++. 是B, count--.
在for循环的过程中, 只要存在hashmap曾经出现过的A的个数, 就更新ans为max(ans, i - map.get(count)).
*/
if(s ==null || s.length() ==0) return 0;
int cnt=0,ans=0;
Map<Integer,Integer> map = new HashMap<>();
map.put(0,0);
for (int i = 1; i <=s.length() ; i++) {
char c =s.charAt(i-1);
if(c=='A') cnt++;
else cnt--;
if(map.containsKey(cnt)){
ans =Math.max(ans,i-map.get(cnt));
}else{
map.put(cnt,i);
}
}
return ans;
}
}