LintCode 1443.最长AB子串

描述
中文
English

给你一个只由字母’A’和’B’组成的字符串s,找一个最长的子串,要求这个子串里面’A’和’B’的数目相等,输出该子串的长度。

解释:把A当做1,把B当做-1,如果平衡,AB的和会为0,那只要ct相同的的位置之间应该是平衡的

class Solution {
public:
    /**
     * @param S: a String consists of a and b
     * @return: the longest of the longest string that meets the condition
     */
     
   

const static int maxn=1e6+5;
string t;
char s[maxn];
int f[maxn],z[maxn];

int getAns(string &S)
{
    // Write your code here
    int len=S.length();
    int ct=0,ans=0;
    memset(f,-1,sizeof(f));
    memset(z,-1,sizeof(z));
    for(int i=0;i<len;i++)
    {
        if(S[i]=='A') ++ct;
        else --ct;
        //cout<<ct<<" ";
        if(ct==0)
        {
            ans=max(ans,i+1);
            continue;
        }

        if(ct<0 && f[-ct]!=-1)
        {
            ans=max(ans,i-f[-ct]);
            continue;
        }
        if(ct>0 && z[ct]!=-1)
        {
            ans=max(ans,i-z[ct]);
            continue;
        }
        if(ct<0) f[-ct]=i;
        else z[ct]=i;
    }
    return ans;
}

};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值