【LintCode】算法题 1443. 最长AB子串

描述

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

  • 这个子串可以为空。
  • s的长度n满足 2<=n<=1000000

样例

给定s="ABAAABBBA",返回8

解释:
子串 s[0,7] 和子串 s[1,8] 满足条件,长度为 8。

给定s="AAAAAA",返回0

解释:
s 中除了空字串,不存在 'A' 和 'B' 数目相等的子串。
扫描二维码关注公众号,回复: 9145925 查看本文章

Java 解法

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) {
        // Write your code here
        int l = S.length();
        int[] numA = new int[l+1];
        int[] numB = new int[l+1];
        int a = 0, b = 0;
        
        for(int i = 0; i < l; i++) {
            if(S.charAt(i) == 'A') a++;
            else b++;
            numA[i+1] = a;
            numB[i+1] = b;
        }
        
        if(a == 0 || b == 0) return 0;
        
        int res = a > b? a : b;
        for(res *= 2; res > 0; res -= 2) {
            for(int i = res; i < l+1; i++) {
                if(numA[i] - numA[i-res]== numB[i] - numB[i-res]) {
                    return res;
                }
            }
        }
        
        return 0;
    }
}

欢迎关注我的知乎专栏【数据池塘】,专注于分享机器学习、数据挖掘相关内容:https://zhuanlan.zhihu.com/datapool

⬇️ 扫描下方二维码关注公众号【数据池塘】 ⬇️

回复【算法】,获取最全面的机器学习算法网络图:

发布了38 篇原创文章 · 获赞 23 · 访问量 7万+

猜你喜欢

转载自blog.csdn.net/cyan_soul/article/details/80765169