lintcode——最长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’ 数目相等的子串。

暴力法:首先由分析可知子串数目只能为偶数,而题目要求最长子串,因此从最长子串遍历开始;分析s中长度为i的子串个数为s.length()+1-sub.length(), 然后判断每个子串对应的A、B字符数量是否相等,若相等直接返回子串的长度即可,无需再继续遍历。

#include <string>
#include <iostream>
using namespace std;

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
        int L = S.length();
        for(int i = (L/2) * 2; i >= 0; i -= 2)//i代表子串的可能长度,只能为偶数
        {
            int count_A = 0;
            int count_B = 0;
            for(int j = 0; j < L + 1 - i; j ++)//j代表长度为i的子串的种类数
            {   
                string sub = S.substr(j,i);
                for(int k = 0; k < sub.length(); k ++)
                {
                    if(sub[k] == 'A')
                        count_A++;
                    if(sub[k] == 'B')
                        count_B++;
                }
                if(count_A == count_B)
                {
                    return sub.length();
                }
            }
        }
    }
};


int main()
{
    Solution s;
    string str("ABAAABBBA");
    cout<<s.getAns(str)<<endl;
    return 0;
}

第二种方法:

#include <string>
#include <iostream>
using namespace std;

class Solution {
public:
    int getAns(string S) 
    {
        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[i] == 'A')
                a ++;
            if(S[i] == 'B')
                b ++;
            numA[i+1] = a;//表示数到第i个A的个数为a,即截止到当前位置的子串A个数为a
            numB[i+1] = b;//表示数到第i个B的个数为b,即截止到当前位置的子串B个数为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;
                }
            }
        }
    }
};

int main()
{
    Solution s;
    string str("ABAAABBBA");
    cout<<s.getAns(str)<<endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/imprincess/article/details/81458259