lintcode练习 - 1443. 最长AB子串

版权声明:原创部分都是自己总结的,如果转载请指明出处。觉得有帮助的老铁,请双击666! https://blog.csdn.net/qq_36387683/article/details/82591275

1443. 最长AB子串

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

样例

给定s="ABAAABBBA",返回8

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

给定s="AAAAAA",返回0

解释:
s 中除了空字串,不存在 'A' 和 'B' 数目相等的子串。

注意事项

  • 这个子串可以为空。
  • s的长度n满足 2<=n<=1000000
class Solution:
    """
    @param S: a String consists of a and b
    @return: the longest of the longest string that meets the condition
    """
    '''
    def getAns(self, S):
        # Write your code here
        n  = len(S)
        dpmax = [0] * (2*n + 1)
        dpmin = [float('inf')] * (2*n+1)
        
        dpmin[n] = 0
        sum = 0
        for i in range(n):
            if S[i] == 'A':
                sum += 1
            else:
                sum -= 1
            
            dpmax[sum + n] = max(dpmax[sum+n], i+1)
            dpmin[sum + n] = min(dpmin[sum+n], i+1)
        
        ans = 0
        for i in range(-n, n+1):
            ans = max(ans, dpmax[i+n] - dpmin[n+i])
        
        return ans
    '''
    def getAns(self, S):
        # Write your code here
        ans = 0
        #定义一个字典,key是AB之间的差距,val是在字符对应坐标
        D = {0: -1}
        if not S:
            return ans
    
        cnt = 0
        for i in range(len(S)):
            if S[i] == 'A':
                cnt += 1
            else:
                cnt -= 1
            #当cnt在字典中的时候,证明该情况出现过,i - D[cnt]之间的字符,AB的数量是相等的,
            if cnt in D:
                ans = max(ans, i - D[cnt])
            else:
                D[cnt] = i
    
        return ans

猜你喜欢

转载自blog.csdn.net/qq_36387683/article/details/82591275