Zookeeper is playing a game. In this game, Zookeeper must use bombs to bomb a string that consists of letters 'A' and 'B'. He can use bombs to bomb a substring which is either "AB" or "BB". When he bombs such a substring, the substring gets deleted from the string and the remaining parts of the string get concatenated.

For example, Zookeeper can use two such operations: AABABBA $\to$ AABBA $\to$ AAA.

Zookeeper wonders what the shortest string he can make is. Can you help him find the length of the shortest string?


-----Input-----

Each test contains multiple test cases. The first line contains a single integer $t$ $(1 \leq t \leq 20000)$  — the number of test cases. The description of the test cases follows.

Each of the next $t$ lines contains a single test case each, consisting of a non-empty string $s$: the string that Zookeeper needs to bomb. It is guaranteed that all symbols of $s$ are either 'A' or 'B'.

It is guaranteed that the sum of $|s|$ (length of $s$) among all test cases does not exceed $2 \cdot 10^5$.


-----Output-----

For each test case, print a single integer: the length of the shortest string that Zookeeper can make.


-----Example-----
Input
3
AAA
BABA
AABBBABBBB

Output
3
2
0



-----Note-----

For the first test case, you can't make any moves, so the answer is $3$.

For the second test case, one optimal sequence of moves is BABA $\to$ BA. So, the answer is $2$.

For the third test case, one optimal sequence of moves is AABBBABBBB $\to$ AABBBABB $\to$ AABBBB $\to$ ABBB $\to$ AB $\to$ (empty string). So, the answer is $0$.

Difficulty: EASY

Solutions:
import sys, collections, math, itertools
INF = sys.maxsize

def get_ints():
	return map(int, sys.stdin.readline().strip().split())

def get_array():
	return list(map(int, sys.stdin.readline().strip().split()))

def input():
	return sys.stdin.readline().strip()
mod = 1000000007
for _ in range(int(input())):
	s = input()
	arr = []
	for i in range(len(s)):
		if not arr:
			arr.append(s[i])
		elif s[i] == 'B' and (arr[-1] == 'B' or arr[-1] == 'A'):
			arr.pop()
		else:
			arr.append(s[i])
	print(len(arr))


for _ in range(int(input())):
	a = list(input())
	counta = 0
	countb = 0
	for i in range(0, len(a)):
		if a[i] == 'A':
			counta += 1
		else:
			countb += 1
			if counta > 0:
				counta -= 1
				countb -= 1
	if countb % 2 == 0:
		countb = 0
	else:
		countb = 1
	print(counta + countb)


import os
import sys
input = sys.stdin.readline

def main():
	num = 0
	s = input()
	num = int(s)
	for _ in range(num):
		string = input()
		ab_index = []
		rs = []
		for (i, s) in enumerate(string):
			if s == 'A':
				ab_index.append(i)
				rs.append(1)
			elif s == 'B':
				if len(ab_index) > 0:
					rs[ab_index[-1]] = 0
					ab_index.pop()
					rs.append(0)
				else:
					ab_index.append(i)
					rs.append(1)
		print(sum(rs))
main()


import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
	word = list(map(str, input().strip()))
	n = int(len(word))
	stac = []
	for i in range(n):
		if len(stac) == 0:
			stac += [word[i]]
		elif stac[-1] == 'A' and word[i] == 'B':
			stac.pop()
		else:
			stac += [word[i]]
	stac2 = []
	for i in range(len(stac)):
		if len(stac2) == 0:
			stac2 += [stac[i]]
		elif stac2[-1] == 'B' and stac[i] == 'B':
			stac2.pop()
		else:
			stac2 += [stac[i]]
	print(len(stac2))


t = int(input())
while t:
	t -= 1
	s = input()
	ans = 0
	for i in range(len(s)):
		if s[i] == 'A':
			ans += 1
		elif ans > 0:
			ans -= 1
		else:
			ans += 1
	print(ans)


from collections import deque
t = int(input())
for _ in range(t):
	s = input().strip()
	stack = deque()
	for i in s:
		if stack and i == 'B':
			stack.pop()
		else:
			stack.append(i)
	print(len(stack))


import sys
tests = int(sys.stdin.readline())
for i in range(tests):
	string = sys.stdin.readline().strip()
	a_balance = 0
	b_count = 0
	lost_count = 0
	for c in string:
		if c == 'A':
			a_balance += 1
		if c == 'B':
			if a_balance > 0:
				a_balance -= 1
			else:
				b_count += 1
	res = a_balance + b_count % 2
	print(res)


n = int(input())
for i in range(n):
	st = input()
	ans = 0
	b = 0
	for d in st:
		if d == 'A':
			ans += 1
		elif d == 'B':
			if ans == 0:
				b += 1
			ans = max(0, ans - 1)
	print(ans + (b & 1))


for _ in range(int(input())):
	s = input()
	a = s.count('A')
	n = len(s)
	b = n - a
	arr = list(s)
	if a == n:
		print(n)
	elif b == n:
		if n & 1:
			print(1)
		else:
			print(0)
	else:
		ans = [s[0]]
		i = 1
		while i < n:
			if len(ans) == 0:
				ans.append(s[i])
				i += 1
				continue
			if ans[-1] == 'A' and s[i] == 'B' or (ans[-1] == 'B' and s[i] == 'B'):
				ans.pop()
			else:
				ans.append(s[i])
			i += 1
		print(len(ans))


from sys import stdin
for _ in range(int(stdin.readline())):
	string = stdin.readline().strip()
	buffer = [string[0]]
	for i in range(1, len(string)):
		if len(buffer) == 0:
			buffer.append(string[i])
		elif buffer[-1] == 'B' and string[i] == 'B':
			buffer.pop()
		elif buffer[-1] == 'A' and string[i] == 'B':
			buffer.pop()
		else:
			buffer.append(string[i])
	print(len(buffer))


import os, io, sys, time, collections, math, pprint, itertools as it, operator as op, bisect as bs, functools as fn
(maxx, localsys, mod) = (float('inf'), 0, int(1000000000.0 + 7))
nCr = lambda n, r: reduce(mul, range(n - r + 1, n + 1), 1) // factorial(r)
ceil = lambda n, x: (n + x - 1) // x
(osi, oso) = ('/home/priyanshu/Documents/cp/input.txt', '/home/priyanshu/Documents/cp/output.txt')
if os.path.exists(osi):
	sys.stdin = open(osi, 'r')
	sys.stdout = open(oso, 'w')
input = sys.stdin.readline

def maps():
	return map(int, input().split())
for _ in range(int(input())):
	s = input().rstrip('\n')
	(st, i, n, t) = ([], 0, len(s), 0)
	while i < n:
		if s[i] == 'B' and st and (st[-1] == 'A'):
			st.pop()
		else:
			st.append(s[i])
		i += 1
	if st:
		prev = st[0]
		for i in st:
			if i == prev and i == 'B':
				t += 1
			prev = i
	print(len(st) - t // 2 * 2)


from collections import defaultdict as dd
import sys
input = sys.stdin.readline
t = int(input())
while t:
	s = input().split()[0]
	st = []
	for i in range(len(s)):
		if s[i] == 'A':
			st.append('A')
		elif st and st[-1] == 'A':
			st.pop()
		else:
			st.append('B')
	i = len(st) - 1
	ans = len(st)
	while i > 0:
		a = st[i]
		b = st[i - 1]
		if a == 'B' and b == 'B':
			ans -= 2
			i -= 2
		else:
			i -= 1
	print(ans)
	t -= 1


import math
import random
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
import sys
from collections import defaultdict
mod = 10 ** 9 + 7
mod1 = 998244353
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

class TreeNode:

	def __init__(self, k, v):
		self.key = k
		self.value = v
		self.left = None
		self.right = None
		self.parent = None
		self.height = 1
		self.num_left = 1
		self.num_total = 1

class AvlTree:

	def __init__(self):
		self._tree = None

	def add(self, k, v):
		if not self._tree:
			self._tree = TreeNode(k, v)
			return
		node = self._add(k, v)
		if node:
			self._rebalance(node)

	def _add(self, k, v):
		node = self._tree
		while node:
			if k < node.key:
				if node.left:
					node = node.left
				else:
					node.left = TreeNode(k, v)
					node.left.parent = node
					return node.left
			elif node.key < k:
				if node.right:
					node = node.right
				else:
					node.right = TreeNode(k, v)
					node.right.parent = node
					return node.right
			else:
				node.value = v
				return

	@staticmethod
	def get_height(x):
		return x.height if x else 0

	@staticmethod
	def get_num_total(x):
		return x.num_total if x else 0

	def _rebalance(self, node):
		n = node
		while n:
			lh = self.get_height(n.left)
			rh = self.get_height(n.right)
			n.height = max(lh, rh) + 1
			balance_factor = lh - rh
			n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right)
			n.num_left = 1 + self.get_num_total(n.left)
			if balance_factor > 1:
				if self.get_height(n.left.left) < self.get_height(n.left.right):
					self._rotate_left(n.left)
				self._rotate_right(n)
			elif balance_factor < -1:
				if self.get_height(n.right.right) < self.get_height(n.right.left):
					self._rotate_right(n.right)
				self._rotate_left(n)
			else:
				n = n.parent

	def _remove_one(self, node):
		replacement = node.left or node.right
		if node.parent:
			if AvlTree._is_left(node):
				node.parent.left = replacement
			else:
				node.parent.right = replacement
			replacement.parent = node.parent
			node.parent = None
		else:
			self._tree = replacement
			replacement.parent = None
		node.left = None
		node.right = None
		node.parent = None
		self._rebalance(replacement)

	def _remove_leaf(self, node):
		if node.parent:
			if AvlTree._is_left(node):
				node.parent.left = None
			else:
				node.parent.right = None
			self._rebalance(node.parent)
		else:
			self._tree = None
		node.parent = None
		node.left = None
		node.right = None

	def remove(self, k):
		node = self._get_node(k)
		if not node:
			return
		if AvlTree._is_leaf(node):
			self._remove_leaf(node)
			return
		if node.left and node.right:
			nxt = AvlTree._get_next(node)
			node.key = nxt.key
			node.value = nxt.value
			if self._is_leaf(nxt):
				self._remove_leaf(nxt)
			else:
				self._remove_one(nxt)
			self._rebalance(node)
		else:
			self._remove_one(node)

	def get(self, k):
		node = self._get_node(k)
		return node.value if node else -1

	def _get_node(self, k):
		if not self._tree:
			return None
		node = self._tree
		while node:
			if k < node.key:
				node = node.left
			elif node.key < k:
				node = node.right
			else:
				return node
		return None

	def get_at(self, pos):
		x = pos + 1
		node = self._tree
		while node:
			if x < node.num_left:
				node = node.left
			elif node.num_left < x:
				x -= node.num_left
				node = node.right
			else:
				return (node.key, node.value)
		raise IndexError('Out of ranges')

	@staticmethod
	def _is_left(node):
		return node.parent.left and node.parent.left == node

	@staticmethod
	def _is_leaf(node):
		return node.left is None and node.right is None

	def _rotate_right(self, node):
		if not node.parent:
			self._tree = node.left
			node.left.parent = None
		elif AvlTree._is_left(node):
			node.parent.left = node.left
			node.left.parent = node.parent
		else:
			node.parent.right = node.left
			node.left.parent = node.parent
		bk = node.left.right
		node.left.right = node
		node.parent = node.left
		node.left = bk
		if bk:
			bk.parent = node
		node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
		node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
		node.num_left = 1 + self.get_num_total(node.left)

	def _rotate_left(self, node):
		if not node.parent:
			self._tree = node.right
			node.right.parent = None
		elif AvlTree._is_left(node):
			node.parent.left = node.right
			node.right.parent = node.parent
		else:
			node.parent.right = node.right
			node.right.parent = node.parent
		bk = node.right.left
		node.right.left = node
		node.parent = node.right
		node.right = bk
		if bk:
			bk.parent = node
		node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
		node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
		node.num_left = 1 + self.get_num_total(node.left)

	@staticmethod
	def _get_next(node):
		if not node.right:
			return node.parent
		n = node.right
		while n.left:
			n = n.left
		return n

class SegmentTree1:

	def __init__(self, data, default=300006, func=lambda a, b: min(a, b)):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)

class SegmentTree:

	def __init__(self, data, default=0, func=lambda a, b: a + b):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)

class Factorial:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorials = [1, 1]
		self.invModulos = [0, 1]
		self.invFactorial_ = [1, 1]

	def calc(self, n):
		if n <= -1:
			print('Invalid argument to calculate n!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.factorials):
			return self.factorials[n]
		nextArr = [0] * (n + 1 - len(self.factorials))
		initialI = len(self.factorials)
		prev = self.factorials[-1]
		m = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * i % m
		self.factorials += nextArr
		return self.factorials[n]

	def inv(self, n):
		if n <= -1:
			print('Invalid argument to calculate n^(-1)')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		p = self.MOD
		pi = n % p
		if pi < len(self.invModulos):
			return self.invModulos[pi]
		nextArr = [0] * (n + 1 - len(self.invModulos))
		initialI = len(self.invModulos)
		for i in range(initialI, min(p, n + 1)):
			next = -self.invModulos[p % i] * (p // i) % p
			self.invModulos.append(next)
		return self.invModulos[pi]

	def invFactorial(self, n):
		if n <= -1:
			print('Invalid argument to calculate (n^(-1))!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.invFactorial_):
			return self.invFactorial_[n]
		self.inv(n)
		nextArr = [0] * (n + 1 - len(self.invFactorial_))
		initialI = len(self.invFactorial_)
		prev = self.invFactorial_[-1]
		p = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * self.invModulos[i % p] % p
		self.invFactorial_ += nextArr
		return self.invFactorial_[n]

class Combination:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorial = Factorial(MOD)

	def ncr(self, n, k):
		if k < 0 or n < k:
			return 0
		k = min(k, n - k)
		f = self.factorial
		return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD

def powm(a, n, m):
	if a == 1 or n == 0:
		return 1
	if n % 2 == 0:
		s = powm(a, n // 2, m)
		return s * s % m
	else:
		return a * powm(a, n - 1, m) % m

def sort_list(list1, list2):
	zipped_pairs = zip(list2, list1)
	z = [x for (_, x) in sorted(zipped_pairs)]
	return z

def product(l):
	por = 1
	for i in range(len(l)):
		por *= l[i]
	return por

def binarySearchCount(arr, n, key):
	left = 0
	right = n - 1
	count = 0
	while left <= right:
		mid = int((right + left) / 2)
		if arr[mid] < key:
			count = mid + 1
			left = mid + 1
		else:
			right = mid - 1
	return count

def countdig(n):
	c = 0
	while n > 0:
		n //= 10
		c += 1
	return c

def binary(x, length):
	y = bin(x)[2:]
	return y if len(y) >= length else '0' * (length - len(y)) + y

def countGreater(arr, n, k):
	l = 0
	r = n - 1
	leftGreater = n
	while l <= r:
		m = int(l + (r - l) / 2)
		if arr[m] > k:
			leftGreater = m
			r = m - 1
		else:
			l = m + 1
	return n - leftGreater

class TrieNode:

	def __init__(self):
		self.children = [None] * 26
		self.isEndOfWord = False

class Trie:

	def __init__(self):
		self.root = self.getNode()

	def getNode(self):
		return TrieNode()

	def _charToIndex(self, ch):
		return ord(ch) - ord('a')

	def insert(self, key):
		pCrawl = self.root
		length = len(key)
		for level in range(length):
			index = self._charToIndex(key[level])
			if not pCrawl.children[index]:
				pCrawl.children[index] = self.getNode()
			pCrawl = pCrawl.children[index]
		pCrawl.isEndOfWord = True

	def search(self, key):
		pCrawl = self.root
		length = len(key)
		for level in range(length):
			index = self._charToIndex(key[level])
			if not pCrawl.children[index]:
				return False
			pCrawl = pCrawl.children[index]
		return pCrawl != None and pCrawl.isEndOfWord

class Node:

	def __init__(self, data):
		self.data = data
		self.count = 0
		self.left = None
		self.right = None

class BinaryTrie:

	def __init__(self):
		self.root = Node(0)

	def insert(self, pre_xor):
		self.temp = self.root
		for i in range(31, -1, -1):
			val = pre_xor & 1 << i
			if val:
				if not self.temp.right:
					self.temp.right = Node(0)
				self.temp = self.temp.right
				self.temp.count += 1
			if not val:
				if not self.temp.left:
					self.temp.left = Node(0)
				self.temp = self.temp.left
				self.temp.count += 1
		self.temp.data = pre_xor

	def query(self, xor):
		self.temp = self.root
		for i in range(31, -1, -1):
			val = xor & 1 << i
			if not val:
				if self.temp.left and self.temp.left.count > 0:
					self.temp = self.temp.left
				elif self.temp.right:
					self.temp = self.temp.right
			elif self.temp.right and self.temp.right.count > 0:
				self.temp = self.temp.right
			elif self.temp.left:
				self.temp = self.temp.left
			self.temp.count -= 1
		return xor ^ self.temp.data
for ik in range(int(input())):
	s = input()
	n = len(s)
	na = 0
	nb = 0
	ans = n
	for i in range(n):
		if s[i] == 'B':
			if na > 0:
				na -= 1
				ans -= 2
			elif nb > 0:
				nb -= 1
				ans -= 2
			else:
				nb += 1
		else:
			na += 1
	print(ans)


t = int(input())
for tt in range(t):
	s = input()
	stack = []
	i = len(s) - 1
	while i >= 0:
		stack.append(s[i])
		i -= 1
	temp_stack = []
	while len(stack) > 0:
		if len(temp_stack) == 0:
			temp_stack.append(stack[-1])
			stack.pop()
		else:
			if stack[-1] == 'A':
				temp_stack.append(stack[-1])
			else:
				temp_stack.pop()
			stack.pop()
	print(len(temp_stack))


import math
from collections import Counter
try:
	for _ in range(int(input())):
		s = input()
		stack = []
		stack.append(s[0])
		for i in range(1, len(s)):
			if len(stack) > 0 and stack[-1] == 'A' and (s[i] == 'B'):
				stack.pop()
			elif len(stack) > 0 and stack[-1] == 'B' and (s[i] == 'B'):
				stack.pop()
			else:
				stack.append(s[i])
		print(len(stack))
except EOFError as e:
	print(e)


mod = 1000000007
eps = 10 ** (-9)

def main():
	import sys
	input = sys.stdin.readline
	for _ in range(int(input())):
		S = input().rstrip('\n')
		st = []
		for s in S:
			if s == 'A':
				st.append(s)
			elif st:
				if st[-1] == 'A':
					st.pop()
				else:
					st.append('B')
			else:
				st.append('B')
		st2 = []
		for s in st:
			if s == 'A':
				st2.append('A')
			elif st2:
				if st2[-1] == 'B':
					st2.pop()
				else:
					st2.append('B')
			else:
				st2.append(s)
		print(len(st2))
main()


import os, sys
from collections import defaultdict, Counter, deque
from io import BytesIO, IOBase

def main():
	for i in range(int(input())):
		s = input().strip()
		x = deque()
		for j in s:
			if len(x) != 0:
				if j == 'B':
					x.pop()
				else:
					x.append(j)
			else:
				x.append(j)
		print(len(x))
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


import os
import sys
from io import BytesIO, IOBase

def main():
	for _ in range(int(input())):
		s = list(input())
		n = len(s)
		acnt = 0
		bcnt = 0
		for i in s:
			if i == 'A':
				acnt += 1
			elif acnt > 0:
				acnt -= 1
			else:
				bcnt += 1
		print(acnt + bcnt % 2)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


import sys
t = int(input())
for i in range(t):
	s = list(sys.stdin.readline().strip())
	n = len(s)
	a = 0
	b = 0
	for j in range(n):
		if s[j] == 'A':
			a = a + 1
		elif a > 0:
			a = a - 1
		else:
			b = b + 1
	b = b % 2
	print(a + b)


from sys import stdin, stdout
input = stdin.readline
from collections import defaultdict as dd
import math

def geti():
	return map(int, input().strip().split())

def getl():
	return list(map(int, input().strip().split()))

def gets():
	return input()

def geta():
	return int(input())

def print_s(s):
	stdout.write(s + '\n')

def solve():
	for _ in range(geta()):
		s = gets()
		stack = []
		for i in s:
			if i == 'B' and stack:
				stack.pop()
				continue
			stack.append(i)
		stack.pop()
		print(len(stack))
solve()


t = int(input())
while t != 0:
	s = input()
	stack = []
	for i in range(len(s)):
		if len(stack) == 0:
			stack.append(s[i])
		elif s[i] == 'B':
			stack.pop()
		else:
			stack.append(s[i])
	print(len(stack))
	t -= 1


def mi():
	return map(int, input().split())
for _ in range(int(input())):
	s = input()
	a = 0
	b = 0
	for i in s:
		if i == 'A':
			a += 1
		elif a > 0:
			a -= 1
		else:
			b += 1
	print(b % 2 + a)


import sys
from collections import deque
sys.setrecursionlimit(10 ** 7)
input = sys.stdin.readline
f_inf = float('inf')
mod = 10 ** 9 + 7

def resolve():
	t = int(input())
	for _ in range(t):
		S = input().rstrip()
		que = deque()
		for s in S:
			if que and (que[-1] == 'A' and s == 'B' or (que[-1] == 'B' and s == 'B')):
				que.pop()
			else:
				que.append(s)
		print(len(que))
resolve()


n = int(input())
for i in range(0, n):
	ch = input()
	c = 0
	for i in ch:
		if i == 'B' and c != 0:
			c -= 1
		else:
			c = c + 1
	print(c)


from sys import stdin, stdout
from collections import deque
ans = []

def main():
	arr = list(stdin.readline())[:-1]
	stack = deque()
	for item in arr:
		if item == 'A':
			stack.append('A')
		elif len(stack) == 0:
			stack.append('B')
		else:
			stack.pop()
	ans.append(str(len(stack)))
for _ in range(int(input())):
	main()
stdout.write('\n'.join(ans))


import sys
input = sys.stdin.readline
t = int(input())
for tests in range(t):
	S = input().strip()
	Q = []
	for s in S:
		if Q and Q[-1] == 'A' and (s == 'B'):
			Q.pop()
		else:
			Q.append(s)
	X = []
	for q in Q:
		X.append(q)
		if len(X) >= 2 and X[-1] == X[-2] == 'B':
			X.pop()
			X.pop()
	print(len(X))


for _ in range(int(input())):
	s = input()
	n = len(s)
	x = 0
	for i in s:
		if i == 'A':
			x += 1
		elif x:
			x -= 1
	print((n + x) % 2 + x)


import sys
import io, os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
ans = []
for _ in range(int(input())):
	a = 0
	for c in input().decode().rstrip('\r\n'):
		a += 1 if c == 'A' or a == 0 else -1
	ans.append(str(a))
sys.stdout.write('\n'.join(ans))


t = int(input())
for t0 in range(t):
	s = input()
	a = []
	la = 0
	for c in s:
		a.append(c)
		la += 1
		if la >= 2:
			if a[la - 1] == 'B':
				a.pop()
				a.pop()
				la -= 2
	print(la)


t = int(input())
for i in range(t):
	s = str(input())
	q = []
	q.append(s[0])
	for i in range(1, len(s)):
		if s[i] == 'B' and len(q) != 0:
			q.pop(-1)
		else:
			q.append(s[i])
	print(len(q))


def main():
	import sys
	input = sys.stdin.readline
	for _ in range(int(input())):
		s = input().strip()
		t = []
		for i in range(len(s) - 1, -1, -1):
			if s[i] == 'B':
				t.append(s[i])
			elif t and t[-1] == 'B':
				t.pop()
			else:
				t.append('A')
		ans = len(t)
		i = 0
		while i < len(t) - 1:
			if t[i] == 'B' and t[i + 1] == 'B':
				ans -= 2
				i += 2
			else:
				i += 1
		print(ans)
	return 0
main()


def solve():
	s = list(input().strip())
	stack = []
	for l in s:
		if l == 'A':
			stack.append(l)
		elif bool(stack):
			if stack[-1] == 'A':
				del stack[-1]
			else:
				stack.append(l)
		else:
			stack.append(l)
	(i, cnt) = (0, 0)
	while i < len(stack) - 1:
		if stack[i] == 'B' and stack[i + 1] == 'B':
			cnt += 2
			i += 2
		else:
			i += 1
	return len(stack) - cnt
for _ in range(int(input().strip())):
	print(solve())


import sys
read = sys.stdin.read

def main():
	t = int(input())
	m = map(tuple, read().split())
	for s in m:
		a = 0
		b = 0
		for se in s:
			if se == 'A':
				a += 1
			elif a:
				a -= 1
			else:
				b += 1
		ans = a + b % 2
		print(ans)
main()


import sys
t = int(input())
while t > 0:
	t -= 1
	s = str(sys.stdin.readline())
	s = s[:-1]
	n = len(s)
	initial_bs = 0
	final_as = 0
	mid_as = 0
	mid_bs = 0
	ans = 0
	(i, j) = (0, n - 1)
	if s[0] == 'B':
		while i < n and s[i] == 'B':
			i += 1
			initial_bs += 1
	if s[-1] == 'A':
		while j >= 0 and s[j] == 'A':
			j -= 1
			final_as += 1
	k = i
	while i <= k < j + 1:
		while k < j + 1 and s[k] == 'A':
			k += 1
			mid_as += 1
		while k < j + 1 and s[k] == 'B':
			k += 1
			mid_bs += 1
		if mid_as > mid_bs:
			mid_as -= mid_bs
			mid_bs = 0
		else:
			mid_bs -= mid_as
			mid_as = 0
			ans += mid_bs % 2
			mid_bs = 0
	print((ans + initial_bs) % 2 + mid_as + final_as)


TC = int(input())
for tc in range(TC):
	s = input()
	curr = 0
	ans = 0
	for i in range(len(s) - 1, -1, -1):
		if s[i] == 'B':
			curr += 1
		elif curr:
			curr -= 1
		else:
			ans += 1
	if curr % 2 == 1:
		ans += 1
	print(ans)


t = int(input())
for i in range(t):
	s = input()
	n = len(s)
	l = []
	for i in range(n):
		l.append(s[i])
	i = 0
	d = []
	for i in range(n):
		if len(d) == 0:
			d.append(l[i])
		elif d[-1] == 'A' and l[i] == 'B':
			d.pop()
		elif d[-1] == 'B' and l[i] == 'B':
			d.pop()
		else:
			d.append(l[i])
	print(len(d))


test_case = int(input())
for i in range(test_case):
	str1 = input()
	ans = 0
	for s in str1:
		if s == 'B' and ans != 0:
			ans -= 1
		else:
			ans += 1
	print(ans)


t = int(input())
for _ in range(t):
	s = input()
	l = len(s)
	i = 0
	ans = 0
	if 'A' not in s:
		ans = l % 2
	else:
		cnt = 0
		bcnt = 0
		for i in range(l):
			if s[i] == 'A':
				cnt += 1
			elif cnt:
				cnt -= 1
			elif not bcnt:
				bcnt += 1
			elif bcnt:
				bcnt -= 1
			else:
				ans += 1
		if cnt:
			ans += cnt
		if bcnt:
			ans += bcnt
	print(ans)


def check(a, b):
	if a == 'A' and b == 'B':
		return 1
	elif a == 'B' and b == 'B':
		return 1
	else:
		return 0
for j in range(int(input())):
	a = input()
	b = list(a)
	(i, c, ll, st, stt) = (0, 0, len(b), [], [])
	for i in range(ll - 1, -1, -1):
		st.append(b[i])
	stt.append(st[-1])
	st.pop()
	while i < ll and len(st) > 0:
		if len(stt) != 0 and check(stt[-1], st[-1]):
			stt.pop()
			st.pop()
			ll -= 2
			c += 1
			i -= 1
		else:
			stt.append(st[-1])
			st.pop()
			i += 1
	print(len(a) - 2 * c)


class node:

	def __init__(self, data):
		self.next = None
		self.data = data

class stack:
	x = 0

	def __init__(self):
		self.head = None

	def push(self, data):
		add = node(data)
		if self.head == None:
			self.head = add
			self.x = 1
		else:
			add1 = self.head
			self.head = add
			self.head.next = add1
			self.x += 1

	def isemp(self):
		if self.head == None:
			return True
		else:
			return False

	def pop(self):
		if self.head == None:
			print('not possible')
		else:
			t = self.head.data
			add = self.head.next
			del self.head
			self.head = add
			self.x -= 1
			return t

	def prin(self):
		if self.head == None:
			print()
		else:
			add = self.head
			while add != None:
				print(add.data, end=' ')
				add = add.next
			print()

	def length(self):
		return self.x
for _ in range(int(input())):
	st = input()
	s = stack()
	for i in st:
		if s.isemp():
			s.push(i)
		else:
			t = s.pop()
			if t == 'B' and i == 'B':
				continue
			elif t == 'B' and i == 'A':
				s.push(t)
				s.push(i)
			elif t == 'A' and i == 'A':
				s.push(t)
				s.push(i)
			elif t == 'A' and i == 'B':
				continue
	print(s.length())


from sys import stdin, stdout
import math, sys, heapq
from itertools import permutations, combinations
from collections import defaultdict, deque, OrderedDict
from os import path
import random
import bisect as bi

def yes():
	print('YES')

def no():
	print('NO')
if path.exists('input.txt'):
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')

	def I():
		return int(input())

	def In():
		return map(int, input().split())
else:

	def I():
		return int(stdin.readline())

	def In():
		return map(int, stdin.readline().split())

def dict(a):
	d = {}
	for x in a:
		if d.get(x, -1) != -1:
			d[x] += 1
		else:
			d[x] = 1
	return d

def find_gt(a, x):
	i = bi.bisect_left(a, x)
	if i != len(a):
		return i
	else:
		return -1

def main():
	try:
		l = input()
		ans = 0
		i = 0
		(noa, nob) = (0, 0)
		while i < len(l):
			if l[i] == 'A':
				noa += 1
			elif noa > 0:
				noa -= 1
			elif nob > 0:
				nob -= 1
			else:
				nob += 1
			i += 1
		print(noa + nob)
	except:
		pass
M = 998244353
P = 1000000007
for _ in range(I()):
	main()


import os
import sys
from io import BytesIO, IOBase
import heapq as h
from bisect import bisect_left, bisect_right
from types import GeneratorType
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		import os
		self.os = os
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			self.os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
import time
start_time = time.time()
import collections as col
import math, string
from functools import reduce

def getInts():
	return [int(s) for s in input().split()]

def getInt():
	return int(input())

def getStrs():
	return [s for s in input().split()]

def getStr():
	return input()

def listStr():
	return list(input())
MOD = 10 ** 9 + 7

def solve():
	S = listStr()
	N = len(S)
	(a, b) = (0, 0)
	ans = N
	B = []
	for j in range(N - 1, -1, -1):
		if S[j] == 'B':
			B.append(j)
		if S[j] == 'A':
			if B:
				B.pop()
				ans -= 2
	ans -= len(B) // 2 * 2
	return ans
for _ in range(getInt()):
	print(solve())


import os
import sys
from io import BytesIO, IOBase
import math
from decimal import *
getcontext().prec = 25
from itertools import permutations
MOD = pow(10, 9) + 7
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
for _ in range(int(input())):
	l = input()
	s = []
	for i in range(len(l)):
		if s:
			if l[i] == 'A':
				s.append('A')
			else:
				s.pop(-1)
		else:
			s.append(l[i])
	print(len(s))


from itertools import permutations
from collections import defaultdict
from math import *
import os
import sys
from io import BytesIO, IOBase
from heapq import nlargest
from bisect import *
import copy
import itertools
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))

def input():
	return sys.stdin.readline().rstrip('\r\n')
t = int(input())
while t:
	t -= 1
	s = input()
	n = len(s)
	(c1, c2, c) = (0, 0, 0)
	for i in range(n):
		if s[i] == 'A':
			c1 += 1
		elif c1 > 0:
			c1 -= 1
		elif c2 == 0:
			c2 += 1
		else:
			c2 = 0
	print(c1 + c2)


import sys
import math
from collections import defaultdict, Counter
input = sys.stdin.readline

def print(x):
	sys.stdout.write(str(x) + '\n')
t = int(input())
for i in range(t):
	s = input().strip()
	n = len(s)
	ans = n
	a = 0
	b = 0
	for j in range(n):
		if s[j] == 'B':
			if a:
				a -= 1
				ans -= 2
			elif b:
				ans -= 2
				b = 0
			else:
				b = 1
		else:
			a += 1
	print(ans)


for _ in ' ' * int(input()):
	s = input()
	if 'B' not in s:
		print(len(s))
	elif 'A' not in s:
		print(len(s) % 2)
	else:
		sm = 0
		n = len(s)
		cnt = 0
		ind = ''.join(s).rindex('B')
		for i in range(ind + 1):
			if s[i] == 'A':
				sm += 1
			if s[i] == 'B':
				if sm > 0:
					sm -= 1
				else:
					cnt += 1
		print(cnt % 2 + sm + (n - 1 - ind))


cases = int(input())
for t in range(cases):
	s = input()
	l = [s[0]]
	for i in s[1:]:
		if l and i == 'B':
			l.pop()
		else:
			l.append(i)
	print(len(l))


from collections import defaultdict
import sys
input = sys.stdin.readline
t = int(input())
for i in range(t):
	ans = 0
	str_ = [i for i in input() if i != '\n']
	stack = []
	for i in str_:
		if i == 'A':
			stack.append('A')
		elif len(stack) > 0:
			stack.pop()
		else:
			stack.append('B')
	print(len(stack))


for t in range(int(input())):
	s = input()
	r = 0
	for c in s:
		if c == 'B' and r > 0:
			r -= 1
		else:
			r += 1
	print(r)


T = int(input())
for t in range(T):
	s = input()
	ans = 0
	for i in s:
		if i == 'B' and ans != 0:
			ans -= 1
		else:
			ans += 1
	print(ans)


from math import *
from bisect import *
from collections import *
from random import *
from decimal import *
from itertools import *
import sys
input = sys.stdin.readline

def inp():
	return int(input())

def st():
	return input().rstrip('\n')

def lis():
	return list(map(int, input().split()))

def ma():
	return map(int, input().split())
t = inp()
while t:
	t -= 1
	s = st()
	stack = []
	for i in range(len(s)):
		stack.append(s[i])
		while len(stack) != 0 and len(stack) - 1:
			x = stack[-1]
			y = stack[-2]
			if x == y == 'B' or (x == 'B' and y == 'A'):
				stack.pop()
				stack.pop()
			else:
				break
	print(len(stack))


q = int(input())
for i in range(q):
	w = input()
	e = 0
	for i in w:
		if e > 0 and i == 'B':
			e -= 1
		else:
			e += 1
	print(e)


import sys, math
from collections import deque, defaultdict
import operator as op
from functools import reduce
sys.setrecursionlimit(10 ** 6)
I = sys.stdin.readline

def ii():
	return int(I().strip())

def li():
	return list(map(int, I().strip().split()))

def mi():
	return map(int, I().strip().split())

def ncr(n, r):
	r = min(r, n - r)
	numer = reduce(op.mul, range(n, n - r, -1), 1)
	denom = reduce(op.mul, range(1, r + 1), 1)
	return numer // denom

def gcd(x, y):
	while y:
		(x, y) = (y, x % y)
	return x

def valid(row, col, rows, cols, rcross, lcross):
	return rows[row] == 0 and cols[col] == 0 and (rcross[col + row] == 0) and (lcross[col - row] == 0)

def main():
	ans = ''
	for _ in range(ii()):
		s = I().strip()
		cnta = 0
		cntb = 0
		for i in s:
			if i == 'A':
				cnta += 1
			elif cnta > 0:
				cnta -= 1
			elif cntb > 0:
				cntb -= 1
			else:
				cntb += 1
		ans += str(cntb + cnta) + '\n'
	print(ans)
main()


import sys

def input():
	return sys.stdin.readline().rstrip()
t = int(input())
for j in range(t):
	inp = input()
	remainings = []
	i = 0
	while i < len(inp):
		if len(remainings) > 0:
			temp = remainings[-1] + inp[i]
			if temp == 'AB' or temp == 'BB':
				remainings.pop()
				i += 1
				continue
		if inp[i:i + 2] == 'AB' or inp[i:i + 2] == 'BB':
			i += 1
		else:
			remainings.append(inp[i])
		i += 1
	print(len(remainings))


T = int(input())
for t in range(T):
	s = input()
	nba = 0
	ends_b = False
	removed = 0
	for i in range(len(s)):
		if s[i] == 'B':
			if nba > 0:
				nba -= 1
				removed += 2
			elif ends_b:
				removed += 2
				ends_b = False
			else:
				ends_b = True
		elif s[i] == 'A':
			nba += 1
	print(len(s) - removed)


T = int(input())
for _ in range(T):
	s = input()
	cA = 0
	cB = 0
	last = ' '
	for k in range(len(s)):
		if s[k] == 'A':
			if k == 0:
				cA = 1
			elif last == 'A':
				cA += 1
			else:
				cA = 1
			last = 'A'
		elif k == 0:
			cB = 1
		else:
			if cA and last == 'A':
				cA -= 1
			else:
				cB = (cB + 1) % 2
			if cA:
				last = 'A'
			elif cB:
				last = 'B'
			else:
				last = ' '
	print(cA + cB)


for _ in range(int(input())):
	s = input()
	ca = 0
	for each in s:
		if not ca or each == 'A':
			ca += 1
		else:
			ca -= 1
	print(ca)


import sys
input = sys.stdin.readline

class Block:
	letter: int
	size: int

	def __init__(self, letter, size):
		self.letter = letter
		self.size = size
AORD = ord('A')
T = int(input())

def add_block(b, letter, size):
	if not b or b[-1].letter != letter:
		b.append(Block(letter, size))
	else:
		b[-1].size += size
for t in range(T):
	A = [1 if c == 'B' else 0 for c in input() if ord(c) >= AORD]
	N = len(A)
	blocks = []
	letter = A[0]
	size = 1
	for i in range(1, N):
		if A[i] == letter:
			size += 1
		else:
			blocks.append(Block(letter=letter, size=size))
			letter = A[i]
			size = 1
	blocks.append(Block(letter=letter, size=size))
	while True:
		i = 0
		new_blocks = []
		while i < len(blocks):
			bi = blocks[i]
			bj = blocks[i + 1] if i + 1 < len(blocks) else blocks[i]
			if bi.letter == 0 and bj.letter == 1:
				bomb = min(bi.size, bj.size)
				if bi.size > bomb:
					add_block(new_blocks, bi.letter, bi.size - bomb)
				elif bj.size > bomb:
					add_block(new_blocks, bj.letter, bj.size - bomb)
				i += 2
			else:
				new_blocks.append(bi)
				i += 1
		improved = len(new_blocks) < len(blocks)
		blocks = new_blocks
		if not improved:
			break
	for b in new_blocks:
		if b.letter == 1:
			b.size %= 2
	ans = 0
	for b in blocks:
		ans += b.size
	print(ans)


from collections import defaultdict
t = int(input())
for _ in range(t):
	s = input()
	a = 0
	b = 0
	i = len(s) - 1
	ans = 0
	while i >= 0:
		if s[i] == 'B':
			while i >= 0 and s[i] == 'B':
				i -= 1
				b += 1
		else:
			while i >= 0 and s[i] == 'A':
				a += 1
				i -= 1
			if b >= a:
				b -= a
				a = 0
			else:
				a -= b
				ans += a
				a = 0
				b = 0
	if b % 2 != 0:
		ans += 1
	print(ans)


from collections import defaultdict, Counter, deque
from math import sqrt, log10, log, floor, factorial, gcd
from bisect import bisect_left, bisect_right
from itertools import permutations, combinations
import sys, io, os
input = sys.stdin.readline
inf = float('inf')
mod = 10 ** 9 + 7

def yn(a):
	print('YES' if a else 'NO')
ceil = lambda a, b: (a + b - 1) // b
t = int(input())
for test in range(t):
	s = input().strip()
	l = 0
	for i in s:
		if not l or i != 'B':
			l += 1
		else:
			l -= 1
	print(l)


t = int(input())
for _ in range(t):
	s = input()
	b = []
	for c in s:
		if len(b) == 0 or c == 'A':
			b.append(c)
		else:
			b.pop()
	print(len(b))


t = int(input())
for _ in range(t):
	s = list(input())
	if 'B' not in s:
		print(len(s))
		continue
	if 'A' not in s:
		print(len(s) % 2)
		continue
	countb = 0
	counta = 0
	ans = 0
	for i in range(len(s) - 1, -1, -1):
		if s[i] == 'B':
			countb += 1
		else:
			if countb == 0:
				ans += 1
				continue
			countb -= 1
	ans += countb % 2
	print(ans)


for i in range(int(input())):
	s = input()
	ans = 0
	for j in s:
		if j == 'B' and ans != 0:
			ans -= 1
		else:
			ans += 1
	print(ans)


t = int(input())
for _ in range(t):
	s = input()
	x = 0
	n = len(s)
	ans = 0
	g = 0
	i = 0
	while i < n:
		if s[i] == 'A':
			g += 1
		if s[i] == 'B':
			if g > 0:
				g -= 1
			else:
				ans += 1
		i += 1
	print(g + ans % 2)


def red(s):
	out = []
	for char in s:
		if char == 'A':
			out.append('A')
		elif len(out) > 0:
			out.pop()
		else:
			out.append('B')
	return len(out)
t = int(input())
for _ in range(t):
	s = input()
	print(red(s))


def solution(s):
	stack = []
	for c in s:
		if c == 'A':
			stack.append('A')
		elif stack:
			del stack[-1]
		else:
			stack.append('B')
	return len(stack)
t = int(input())
for _ in range(t):
	print(solution(input()))


for _ in range(int(input())):
	a = list(input())
	s = []
	l = 0
	for i in a:
		if i == 'A':
			s.append('A')
			l += 1
		elif l > 0:
			s.pop()
			l -= 1
		else:
			s.append('B')
			l += 1
	print(l)


import sys
input = sys.stdin.readline
a = int(input())
for x in range(a):
	b = input()
	t = []
	h = []
	n = 0
	m = 0
	for y in b:
		if y == 'B':
			if n == 0 and m == 0:
				m += 1
			elif n > 0:
				n -= 1
			elif m > 0:
				m -= 1
		if y == 'A':
			n += 1
	print(m + n)


import sys
input = sys.stdin.readline

def inp():
	return int(input())

def inlt():
	return list(map(int, input().split()))

def insr():
	s = input()
	return list(s[:len(s) - 1])

def invr():
	return map(int, input().split())

def solution():
	t = inp()
	for _ in range(t):
		s = input().strip()
		print(solve(s))

def solve(s):
	cnt = 0
	for c in s:
		if c == 'A' or not cnt:
			cnt += 1
		else:
			cnt -= 1
	return cnt
solution()


for _ in range(int(input())):
	s = input()
	c = 0
	i = 0
	for i in s:
		if i == 'A' or c == 0:
			c += 1
		else:
			c -= 1
	print(c)


for _ in range(int(input())):
	s = input()
	n = len(s)
	th = [True] * n
	st = []
	for i in range(n):
		if s[i] == 'A':
			st.append(i)
		elif len(st) > 0:
			th[st.pop()] = False
			th[i] = False
	print(len(''.join([s[i] for i in range(n) if th[i]]).replace('BB', '')))


from sys import stdin
for i in range(int(input())):
	string = input()
	stack = []
	for i in string:
		if len(stack) == 0:
			stack.append(i)
		elif (stack[-1] == 'A' or stack[-1] == 'B') and i == 'B':
			stack.pop(-1)
		else:
			stack.append(i)
	print(len(stack))


import itertools
t = int(input())
for _ in range(t):
	s = input()
	stk = []
	for c in s:
		if len(stk) == 0:
			stk.append(c)
		elif stk[-1] == 'A' and c == 'B':
			stk.pop()
		else:
			stk.append(c)
	result = len(stk)
	for (k, v) in itertools.groupby(stk):
		currNum = len(list(v))
		if k == 'B' and currNum >= 2:
			if currNum % 2 == 0:
				result -= currNum
			else:
				result -= currNum - 1
	print(result)


import sys
import os
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
mod = 10 ** 9 + 7

def lcm(x, y):
	return x * y / gcd(x, y)

def fact(x, mod=mod):
	ans = 1
	for i in range(1, x + 1):
		ans = ans * i % mod
	return ans

def arr2D(n, m, default=0):
	return [[default for j in range(m)] for i in range(n)]

def arr3D(n, m, r, default=0):
	return [[[default for k in range(r)] for j in range(m)] for i in range(n)]

def sortDictV(x):
	return {k: v for (k, v) in sorted(x.items(), key=lambda item: item[1])}

def solve(lst):
	lst = list(lst)
	lst1 = []
	for i in lst:
		if i == 'A':
			lst1.append('A')
		elif lst1 != [] and lst1[-1] == 'A':
			lst1.pop()
		else:
			lst1.append('B')
	lst2 = []
	for i in lst1:
		if i == 'A':
			lst2.append('A')
		elif lst2 != [] and lst2[-1] == 'B':
			lst2.pop()
		else:
			lst2.append('B')
	return len(lst2)
for a in range(int(input())):
	lst = input()
	print(solve(lst))


from itertools import groupby
t = int(input())
for _ in range(t):
	ans = 0
	for c in input():
		if c == 'B' and ans > 0:
			ans -= 1
		else:
			ans += 1
	print(ans)


t = int(input())
for i in range(t):
	a = input()
	s = 0
	for i in a:
		if i == 'B' and s != 0:
			s += -1
		else:
			s += 1
	print(s)


import sys
input = sys.stdin.readline
T = int(input())
for case in range(T):
	s = input()
	s = s[:-1]
	stack = []
	N = len(s)
	for i in range(N):
		if s[i] == 'A':
			stack.append('A')
		elif stack:
			stack.pop()
		else:
			stack.append('B')
	print(len(stack))


def getLength(s):
	stack = []
	for i in range(len(s)):
		if len(stack) == 0:
			stack.append(s[i])
			continue
		if s[i] == 'B':
			if stack[-1] == 'A' or stack[-1] == 'B':
				stack.pop()
				continue
		stack.append(s[i])
	return len(stack)
T = int(input())
for t in range(T):
	s = input()
	print(getLength(s))


from sys import stdin
import sys
tt = int(stdin.readline())
ans = []
for loop in range(tt):
	s = stdin.readline()[:-1]
	q = []
	for i in s:
		q.append(i)
		if len(q) > 1 and q[-2] == 'A' and (q[-1] == 'B'):
			del q[-1]
			del q[-1]
		elif len(q) > 1 and q[-2] == 'B' and (q[-1] == 'B'):
			del q[-1]
			del q[-1]
	ans.append(len(q))
print('\n'.join(map(str, ans)))


def main():
	line = input()
	b = 0
	cant_del = 0
	for i in range(len(line) - 1, -1, -1):
		if line[i] == 'A':
			if b > 0:
				b -= 1
			else:
				cant_del += 1
		else:
			b += 1
	print(b % 2 + cant_del)
t = int(input())
for i in range(t):
	main()


from collections import Counter
import math
import sys
from bisect import bisect, bisect_left, bisect_right
from itertools import permutations

def input():
	return sys.stdin.readline().strip()

def INT():
	return int(input())

def MAP():
	return map(int, input().split())

def LIST(N=None):
	return list(MAP()) if N is None else [INT() for i in range(N)]

def mod():
	return 10 ** 9 + 7
for i in range(INT()):
	s = input()
	n = len(s)
	stack = []
	for i in range(n):
		if not stack:
			stack.append(s[i])
		elif s[i] == 'B':
			del stack[-1]
		else:
			stack.append(s[i])
	print(len(stack))


for _ in range(int(input())):
	a = 0
	for c in input():
		a += 1 if c == 'A' or a == 0 else -1
	print(a)


import sys
import math

def II():
	return int(sys.stdin.readline())

def LI():
	return list(map(int, sys.stdin.readline().split()))

def MI():
	return map(int, sys.stdin.readline().split())

def SI():
	return sys.stdin.readline().strip()
t = II()
for q in range(t):
	s = list(SI())
	a = []
	n = len(s)
	temp = 1
	isA = s[0] == 'A'
	for i in range(1, n):
		if s[i] == s[i - 1]:
			temp += 1
		else:
			a.append(temp)
			temp = 1
	a.append(temp)
	n = len(a)
	if not isA:
		ans = a[0] % 2
	else:
		ans = a[0]
	isA = not isA
	for i in range(1, n):
		if isA:
			ans += a[i]
		elif ans > a[i]:
			ans -= a[i]
		else:
			a[i] -= ans
			a[i] %= 2
			ans = a[i]
		isA = not isA
	print(ans)


from sys import stdin
input = stdin.readline

def A():
	t = int(input())
	for _ in range(t):
		(x1, y1, x2, y2) = map(int, input().split())
		if x2 == x1:
			print(abs(y2 - y1))
		elif y1 == y2:
			print(abs(x2 - x1))
		else:
			print(abs(x2 - x1) + abs(y2 - y1) + 2)

def B():
	t = int(input())
	for _ in range(t):
		n = int(input())
		s = list(input().rstrip())
		(rl, ll, lr, rr) = (0, 0, 0, 0)
		(lcount, rcount) = (0, 0)
		for i in range(0, n - 1):
			if s[i] == '<':
				if s[i + 1] == '>':
					lr += 1
				elif s[i + 1] == '<':
					ll += 1
				lcount += 1
			elif s[i] == '>':
				if s[i + 1] == '>':
					rr += 1
				elif s[i + 1] == '<':
					rl += 1
				rcount += 1
		if s[n - 1] == '<':
			if s[0] == '<':
				ll += 1
			elif s[0] == '>':
				lr += 1
			lcount += 1
		elif s[n - 1] == '>':
			if s[0] == '<':
				rl += 1
			elif s[0] == '>':
				rr += 1
			rcount += 1
		if lcount == 0 or rcount == 0:
			print(n)
		else:
			print(n - ll - lr - rl - rr)

def C():
	t = int(input())
	for _ in range(t):
		s = list(input().rstrip())
		n = len(s)
		i = 0
		remaining = 0
		depth = 0
		j = n - 1
		while j >= i:
			if s[j] == 'A':
				depth += 1
				if depth > 0:
					remaining += 1
					depth = 0
			else:
				depth -= 1
			j -= 1
		remaining += depth % 2
		print(remaining)

def D():
	t = int(input())
	for _ in range(t):
		print()
C()


def f(s):
	c1 = 0
	c2 = 0
	for item in s:
		if item == 'A':
			if c1 < 0:
				c2 -= c1
				c1 = 1
			else:
				c1 += 1
		if item == 'B':
			c1 -= 1
	if c1 < 0:
		c2 -= c1
		c1 = 0
	return c2 % 2 + c1
t = int(input())
for i in range(t):
	print(f(input()))


for _ in range(int(input())):
	a = input()
	ans = 0
	q = []
	for i in range(len(a)):
		if a[i] == 'A':
			q.append('A')
		elif len(q) > 0:
			q.pop(len(q) - 1)
		else:
			q.append(a[i])
	print(len(q))


t = int(input())
for tc in range(t):
	inp = input()
	cnt = 0
	for i in range(len(inp)):
		if inp[i] == 'B' and cnt != 0:
			cnt -= 1
		else:
			cnt += 1
	print(cnt)


import sys
input = lambda : sys.stdin.readline().strip()
inp = lambda : list(map(int, input().split()))
for _ in range(int(input())):
	a = str(input())
	ans = 0
	n = len(a)
	ass = a.count('A')
	bss = a.count('B')
	aa = 0
	bb = 0
	for i in range(n - 1, -1, -1):
		if a[i] == 'B':
			bb += 1
		if a[i] == 'A':
			if bb > 0:
				bb -= 1
			else:
				aa += 1
	print(bb % 2 + aa)


t = int(input())
for _ in range(t):
	s = input()
	a_count = 0
	ans = len(s)
	negs = 0
	for i in range(len(s)):
		if s[i] == 'A':
			a_count += 1
		elif a_count:
			a_count -= 1
			ans -= 2
		else:
			negs += 1
	print(ans - negs + negs % 2)


t = int(input())
for _ in range(t):
	s = input()
	rem = []
	a = 0
	b = 0
	for i in range(len(s)):
		if s[i] == 'A':
			if b > 0:
				rem.append('B' * b)
				b = 0
				a += 1
			else:
				a += 1
		elif a > 0:
			a -= 1
		else:
			b += 1
	rem.append('A' * a)
	rem.append('B' * b)
	s = ''.join(rem)
	b = 0
	r = 0
	for i in range(len(s)):
		if s[i] == 'B':
			b += 1
		else:
			r += b // 2
			b = 0
	r += b // 2
	print(len(s) - r * 2)


t = int(input())
for i in range(t):
	s = input()
	res = 0
	for i in range(len(s)):
		if s[i] == 'B' and res != 0:
			res -= 1
		else:
			res += 1
	print(res)


for i1 in range(int(input())):
	s = input()
	ans = 0
	for i in s:
		if i == 'A':
			ans += 1
		elif ans:
			ans -= 1
		else:
			ans += 1
	print(ans)


for _ in range(int(input())):
	s = input()
	st = []
	for c in s:
		if len(st) and c == 'B':
			st.pop()
		else:
			st.append(c)
	print(len(st))


t = int(input())
for i in range(t):
	r = input()
	k = len(r)
	w = int(k)
	a = 0
	b = 0
	ans = 0
	for i in range(k - 1, -1, -1):
		if r[i] == 'A':
			w -= 1
		else:
			break
	for i in range(w - 1, -1, -1):
		if r[i] == 'B':
			b += 1
		elif b > 0:
			ans -= 2
			b -= 1
	print(k + ans - b + b % 2)


from functools import reduce
import collections
import math
import sys

class Read:

	@staticmethod
	def string():
		return input()

	@staticmethod
	def int():
		return int(input())

	@staticmethod
	def list(delimiter=' '):
		return input().split(delimiter)

	@staticmethod
	def list_int(delimiter=' '):
		return list(map(int, input().split(delimiter)))

def main():
	t = Read.int()
	for _ in range(t):
		a = list(Read.string())
		res = 0
		for i in a:
			if i == 'A':
				res += 1
			elif res > 0:
				res -= 1
			else:
				res += 1
		print(res)
main()


n = int(input())
for _ in range(n):
	l = list(input())
	l1 = list()
	for i in range(0, len(l)):
		if l[i] == 'A':
			l1.append(l[i])
		elif len(l1) > 0:
			l1.pop()
		else:
			l1.append(l[i])
	print(len(l1))


from collections import defaultdict
import sys
input = sys.stdin.readline
t = int(input())
for i in range(t):
	ans = 0
	str_ = [i for i in input() if i != '\n']
	rang = []
	for i in range(len(str_)):
		if str_[i] == 'B':
			if len(rang) == 0 or len(rang[-1]) == 2:
				rang.append([i])
		if str_[i] == 'A':
			if len(rang) != 0 and len(rang[-1]) == 1:
				rang[-1].append(i)
	if len(rang) > 0 and len(rang[-1]) == 1:
		rang[-1].append(len(str_))
	(carry, diff) = (0, 0)
	(ans, left) = (0, 0)
	for i in rang:
		carry += i[0] - diff
		diff = i[1]
		pq = i[1] - i[0]
		if carry < i[1] - i[0]:
			ans += 2 * carry
			pq -= carry
			if pq % 2 == 0:
				ans += pq
			else:
				ans += pq - 1
				left += 1
			carry = 0
		else:
			ans += 2 * pq
			carry -= pq
	if left % 2 == 0:
		ans += left
	else:
		ans += left - 1
	print(len(str_) - ans)


n = int(input())
for i in range(n):
	l = []
	s = str(input())
	for j in range(0, len(s)):
		if len(l) == 0:
			l.append(s[j])
		elif s[j] == 'B' and l[-1] == 'A':
			l.pop()
		else:
			l.append(s[j])
	ans = len(l)
	j = 0
	while j < len(l) - 1:
		if l[j] == l[j + 1] == 'B':
			j = j + 2
			ans = ans - 2
		else:
			j = j + 1
	print(ans)


for _ in range(int(input())):
	a = input()
	n = len(a)
	q = n
	for i in range(n - 1, -1, -1):
		if a[i] == 'B':
			a = a[:i + 1]
			break
	n = len(a)
	stack = []
	v = [0] * n
	for i in range(n - 1, -1, -1):
		if a[i] == 'B':
			stack.append(i)
		elif a[i] == 'A':
			if len(stack) != 0:
				v[i] = 1
				v[stack.pop()] = 1
	t = 0

	def countnva(v):
		x = 0
		for i in range(n):
			if v[i] == 0:
				x += 1
		return x

	def countnvb(v):
		x = 0
		for i in range(n):
			if v[i] == 0 and a[i] == 'A':
				return x // 2 * 2
			if v[i] == 0:
				x += 1
		return x // 2 * 2

	def count(v):
		x = 0
		for i in range(n):
			if v[i] == 1:
				x += 1
		return x
	for i in range(n):
		if v[i] == 0:
			if a[i] == 'A':
				print(countnva(v) + (q - n))
				t = 1
				break
			else:
				t = 1
				print(q - (count(v) + countnvb(v)))
				break
	if t == 0:
		print(q - n)


import sys
input = sys.stdin.readline
for _ in range(int(input())):
	s = input().strip()
	stack = []
	for i in s:
		if stack and i == 'B':
			stack.pop()
		else:
			stack.append(i)
	print(len(stack))


for _ in range(int(input())):
	a = list(input().strip())
	n = len(a)
	st = []
	for i in range(n):
		if a[i] == 'B':
			if st:
				st.pop()
			else:
				st.append(a[i])
		else:
			st.append(a[i])
	print(len(st))


t = int(input())

def solve(s):
	n = len(s)
	ca = 0
	c = 0
	cb = 0
	for i in range(n):
		if s[i] == 'A':
			ca += 1
			c += 1
		else:
			c += 1
			if ca > 0:
				ca -= 1
				c -= 2
			elif cb > 0:
				cb -= 1
				c -= 2
			else:
				cb += 1
	print(c)
for i in range(t):
	s = list(str(input()))
	solve(s)


for _ in range(int(input())):
	s = input()
	l = []
	for i in range(len(s)):
		if s[i] == 'A' or len(l) == 0:
			l.append(s[i])
		elif s[i] == 'B' and (l[-1] == 'B' or l[-1] == 'A'):
			l.pop()
	print(len(l))


import sys
inp = sys.stdin.buffer.readline
inar = lambda : list(map(int, inp().split()))
inin = lambda : int(inp())
inst = lambda : inp().decode().strip()
wrt = sys.stdout.write
pr = lambda *args, end='\n': wrt(' '.join([str(x) for x in args]) + end)
enum = enumerate
inf = float('inf')
cdiv = lambda x, y: -(-x // y)
mod = 1000000007
_T_ = inin()
for _t_ in range(_T_):
	s = inst()
	afound = 0
	bfound = 0
	sm = 0
	for i in s:
		if i == 'B' and afound:
			afound -= 1
		elif i == 'B' and bfound:
			bfound -= 1
		elif i == 'B':
			bfound += 1
		else:
			afound += 1
	print(afound + bfound)


n = int(input())
for i in range(n):
	s = input()
	stack = []
	for letter in s:
		if len(stack) > 0:
			if letter == 'B':
				stack.pop()
			else:
				stack.append(letter)
		else:
			stack.append(letter)
	print(len(stack))


t = int(input())
for _ in range(t):
	s = input()
	n = len(s)
	l = []
	for i in s:
		l.append(i)
		if len(l) > 1:
			if l[-1] == 'B' and l[-2] == 'A' or (l[-1] == 'B' and l[-2] == 'B'):
				n -= 2
				l.pop()
				l.pop()
	print(n)


def main(s):
	res = 0
	stack = []
	for i in s:
		if stack == []:
			stack.append(i)
			continue
		if stack[-1] == 'B' and i == 'B':
			stack.pop()
		elif stack[-1] == 'A' and i == 'B':
			stack.pop()
		else:
			stack.append(i)
	print(len(stack))
n = int(input())
for i in range(n):
	s = input()
	main(s)


import sys
import math
import itertools
import functools
import collections
import operator
import fileinput
import copy
ORDA = 97

def ii():
	return int(input())

def mi():
	return map(int, input().split())

def li():
	return [int(i) for i in input().split()]

def lcm(a, b):
	return abs(a * b) // math.gcd(a, b)

def revn(n):
	return str(n)[::-1]

def dd():
	return collections.defaultdict(int)

def ddl():
	return collections.defaultdict(list)

def sieve(n):
	if n < 2:
		return list()
	prime = [True for _ in range(n + 1)]
	p = 3
	while p * p <= n:
		if prime[p]:
			for i in range(p * 2, n + 1, p):
				prime[i] = False
		p += 2
	r = [2]
	for p in range(3, n + 1, 2):
		if prime[p]:
			r.append(p)
	return r

def divs(n, start=2):
	r = []
	for i in range(start, int(math.sqrt(n) + 1)):
		if n % i == 0:
			if n / i == i:
				r.append(i)
			else:
				r.extend([i, n // i])
	return r

def divn(n, primes):
	divs_number = 1
	for i in primes:
		if n == 1:
			return divs_number
		t = 1
		while n % i == 0:
			t += 1
			n //= i
		divs_number *= t

def prime(n):
	if n == 2:
		return True
	if n % 2 == 0 or n <= 1:
		return False
	sqr = int(math.sqrt(n)) + 1
	for d in range(3, sqr, 2):
		if n % d == 0:
			return False
	return True

def convn(number, base):
	new_number = 0
	while number > 0:
		new_number += number % base
		number //= base
	return new_number

def cdiv(n, k):
	return n // k + (n % k != 0)

def ispal(s):
	for i in range(len(s) // 2 + 1):
		if s[i] != s[-i - 1]:
			return False
	return True
ans = []
for _ in range(ii()):
	s = input()
	t = [0, 0]
	for c in s:
		if c == 'A':
			t[0] += 1
		elif c == 'B' and t[0] > 0:
			t[0] -= 1
		elif c == 'B':
			t[1] = (t[1] + 1) % 2
	ans.append(sum(t))
print(*ans, sep='\n')


t = int(input())
while t > 0:
	t -= 1
	string = input()
	i = 0
	ans = []
	l = len(string)
	while i < l - 1:
		if string[i] == 'A':
			if string[i + 1] == 'B':
				i += 2
			else:
				i += 1
				ans.append('A')
		elif string[i + 1] == 'A':
			i += 1
			ans.append('B')
			if len(ans) > 1:
				ans.pop()
				ans.pop()
		elif len(ans) > 1:
			ans.pop()
			i += 1
		else:
			i += 2
	if i == l - 1:
		if string[i] == 'A':
			ans.append('A')
		else:
			ans.append('B')
			if len(ans) > 1:
				ans.pop()
				ans.pop()
	print(len(ans))


def function(param):
	n = len(param)
	As = 0
	Bs = 0
	for index in range(len(param)):
		if param[index] == 'A':
			As = As + 1
		elif As > 0:
			As = As - 1
		elif Bs == 0:
			Bs = 1
		else:
			Bs = 0
	return As + Bs
total = int(input())
for index in range(total):
	line = input()
	result = function(line)
	print(result)


import sys
from collections import defaultdict as dc
import math
for _ in range(int(input())):
	s = input()
	x = []
	for i in s:
		if i == 'A':
			x.append(i)
		elif x:
			x.pop()
		else:
			x.append(i)
	print(len(x))


for _ in range(int(input())):
	s = input()
	l = len(s)
	count = l
	a = 0
	b = 0
	for x in s:
		if x == 'A':
			a += 1
		elif a == 0:
			b += 1
		else:
			a -= 1
	b = b % 2
	a = a + b
	print(a)


t = int(input())
for i in range(t):
	string = list(input())
	acnt = 0
	bcnt = 0
	lcounter = 0
	for let in string:
		if let == 'A':
			acnt += 1
		elif acnt:
			lcounter += 1
			acnt -= 1
		elif bcnt:
			lcounter += 1
			bcnt -= 1
		else:
			bcnt += 1
	print(len(string) - lcounter * 2)


class Stack:

	def __init__(self):
		self.stack_array = []
		self.stack_size = 0

	def push(self, element):
		self.stack_array.append(element)
		self.stack_size += 1

	def pop(self):
		self.stack_array.pop()
		self.stack_size -= 1

	def peek(self):
		return self.stack_array[-1]

	def isEmpty(self):
		return self.stack_size == 0

def minm_size(s):
	string_stack = Stack()
	for i in s:
		if i == 'B':
			if not string_stack.isEmpty():
				if string_stack.peek() in ['A', 'B']:
					string_stack.pop()
				else:
					string_stack.push(i)
			else:
				string_stack.push(i)
		else:
			string_stack.push(i)
	return string_stack.stack_size

def main():
	outputs = []
	for __ in range(int(input())):
		s = input()
		outputs.append(minm_size(s))
	for output in outputs:
		print(output)
main()


(N,) = map(int, input().split())
for _ in range(N):
	s = input().strip()
	bc = 0
	ra = 0
	for c in s[::-1]:
		if c == 'B':
			bc += 1
		if c == 'A':
			if bc:
				bc -= 1
			else:
				ra += 1
	if bc % 2:
		ra += 1
	print(ra)


import os, sys
from io import IOBase, BytesIO
py2 = round(0.5)
if py2:
	from future_builtins import ascii, filter, hex, map, oct, zip
	range = xrange
BUFSIZE = 8192

class FastIO(BytesIO):
	newlines = 0

	def __init__(self, file):
		self._file = file
		self._fd = file.fileno()
		self.writable = 'x' in file.mode or 'w' in file.mode
		self.write = super(FastIO, self).write if self.writable else None

	def _fill(self):
		s = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
		self.seek((self.tell(), self.seek(0, 2), super(FastIO, self).write(s))[0])
		return s

	def read(self):
		while self._fill():
			pass
		return super(FastIO, self).read()

	def readline(self):
		while self.newlines == 0:
			s = self._fill()
			self.newlines = s.count(b'\n') + (not s)
		self.newlines -= 1
		return super(FastIO, self).readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.getvalue())
			(self.truncate(0), self.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		if py2:
			self.write = self.buffer.write
			self.read = self.buffer.read
			self.readline = self.buffer.readline
		else:
			self.write = lambda s: self.buffer.write(s.encode('ascii'))
			self.read = lambda : self.buffer.read().decode('ascii')
			self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
import sys

class ostream:

	def __lshift__(self, a):
		sys.stdout.write(str(a))
		return self
cout = ostream()
endl = '\n'

def get_input(a=str):
	return a(input())

def get_int_input():
	return get_input(int)

def get_input_arr(a):
	return list(map(a, input().split()))

def get_int_input_arr():
	return get_input_arr(int)

def solve():
	t = get_int_input()
	for _ in range(t):
		st = get_input()
		mark = [True] * len(st)
		ptr_1 = 0
		ptr_2 = 0

		def find_next():
			nonlocal ptr_1, ptr_2
			while ptr_1 < len(st):
				if mark[ptr_1] and st[ptr_1] == 'A':
					break
				ptr_1 += 1
			while ptr_2 < len(st):
				if mark[ptr_2] and st[ptr_2] == 'B' and (ptr_2 > ptr_1):
					break
				ptr_2 += 1
		find_next()
		while ptr_1 < len(st) and ptr_2 < len(st) and (st[ptr_1] == 'A') and (st[ptr_2] == 'B'):
			mark[ptr_1] = False
			mark[ptr_2] = False
			ptr_1 += 1
			ptr_2 += 1
			find_next()
		ptr_1 = 0
		ptr_2 = 0

		def find_next_2():
			nonlocal ptr_1, ptr_2
			while ptr_1 < len(st):
				if mark[ptr_1] and st[ptr_1] == 'B':
					break
				ptr_1 += 1
			while ptr_2 < len(st):
				if st[ptr_2] == 'B' and mark[ptr_2] and (ptr_2 > ptr_1):
					break
				ptr_2 += 1
		find_next_2()
		while ptr_1 < len(st) and ptr_2 < len(st) and (st[ptr_1] == 'B') and (st[ptr_2] == 'B'):
			mark[ptr_1] = False
			mark[ptr_2] = False
			ptr_1 += 1
			ptr_2 += 1
			find_next_2()
		res = 0
		for i in range(len(mark)):
			if mark[i]:
				res += 1
		cout << res << endl

def main():
	solve()
main()


import sys
(_, *inp) = open(0).read().split()
ans = []
for s in inp:
	a = 0
	for c in s:
		a += 1 if c == 'A' or a == 0 else -1
	ans.append(str(a))
sys.stdout.write('\n'.join(ans))


for _ in range(int(input())):
	s = input()
	stack = 0
	prev = ''
	for char in s:
		if stack and char == 'B':
			stack -= 1
		else:
			stack += 1
			prev = char
	print(stack)


def main():
	s = input()
	arr = []
	for i in range(len(s)):
		if len(arr) != 0 and s[i] == 'B':
			arr.pop()
		else:
			arr.append(s[i])
	print(len(arr))
for _ in range(int(input())):
	main()


for _ in range(int(input())):
	l = input()
	v = []
	for i in l:
		if i == 'A':
			v.append(i)
		elif v:
			v.pop()
		else:
			v.append(i)
	print(len(v))


def solve(s):
	countb = 0
	counta = 0
	lasta = 0
	first = True
	for c in s:
		if c == 'A':
			lasta = counta
			counta += 1
			first = False
		elif first:
			countb += 1
		else:
			lasta = counta
			counta -= 1
			if lasta == 1 and counta == 0:
				first = True
	if counta > 0:
		return countb % 2 + counta
	else:
		return (countb - counta) % 2
t = int(input())
for i in range(t):
	s = input()
	print(solve(s))


from collections import deque
for _ in range(int(input())):
	s = input()
	l = deque()
	for c in s:
		if c == 'A':
			l.append(c)
		elif l:
			l.pop()
		else:
			l.append(c)
	print(len(l))


for _ in range(int(input())):
	s = input()
	n = len(s)
	cnt = 0
	i = 0
	ans = 0
	if s.count('B') == 0:
		ans = n
	else:
		(a, b) = (0, 0)
		ans = 0
		while i < n:
			if s[i] == 'A':
				a += 1
				ans += 1
			elif s[i] == 'B':
				b += 1
				if a > 0 and b > 0:
					ans -= 1
					a -= 1
					b -= 1
				elif b % 2 == 0:
					ans -= 1
					b = 0
			i += 1
		ans = a + b
	print(ans)


import os
import math
import statistics
true = True
false = False
from functools import reduce
is_dev = 'vscode' in os.environ
if is_dev:
	inF = open('in.txt', 'r')
	outF = open('out.txt', 'w')

def ins():
	return list(map(int, input_().split(' ')))

def inss():
	return list(input_().split(' '))

def input_():
	if is_dev:
		return inF.readline()[:-1]
	else:
		return input()

def ranin():
	return range(int(input_()))

def print_(data):
	if is_dev:
		outF.write(str(data) + '\n')
	else:
		print(data)
epsilon = 1e-07

def prev_i(ii):
	return (ii - 1) % n

def next_i(ii):
	return (ii + 1) % n
for _ in ranin():
	a = input_()
	if len(a) <= 1:
		print_(len(a))
		continue
	aa = [a[0]]
	idx = 1
	while idx < len(a):
		if a[idx] == 'B':
			if aa:
				aa.pop(0)
			else:
				aa.append(a[idx])
		else:
			aa.append(a[idx])
		idx += 1
	print_(len(aa))
if is_dev:
	outF.close()

	def compare_file():
		print(open('out.txt', 'r').read() == open('outactual.txt', 'r').read())
	compare_file()


tc = int(input())
for i in range(tc):
	s = input()
	run = []
	i = len(s) - 1
	running_b = 0
	while i >= 0:
		if s[i] == 'A':
			run.append(running_b)
		else:
			running_b += 1
		i -= 1
	run.reverse()
	i = len(run) - 1
	ans = 0
	newrun = 0
	absused = 0
	while i >= 0:
		if run[i] - newrun <= 0:
			ans += 1
		else:
			newrun += 1
			absused += 1
		i -= 1
	if (s.count('B') - absused) % 2 == 1:
		ans += 1
	print(ans)


def main():
	t = int(input())
	for _ in range(t):
		s = input()
		n = len(s)
		stored = num_as = total = 0
		for i in range(n - 1, -1, -1):
			if s[i] == 'B':
				stored += 1
			else:
				num_as += 1
				if stored:
					stored -= 1
					total += 1
		num_bs = n - num_as
		if stored:
			total += (num_bs - total) // 2
		print(n - total * 2)
main()


def main():
	for _ in range(int(input())):
		s = input()
		stack = []
		for v in s:
			if not stack:
				stack.append(v)
				continue
			if v == 'B':
				stack.pop()
				continue
			stack.append(v)
		print(len(stack))
main()


t = int(input())
for i in range(t):
	l = []
	s = input()
	for j in s:
		l.append(j)
		if len(l) > 1:
			if l[-1] == 'B' and l[-2] == 'A':
				l.pop()
				l.pop()
		if len(l) > 1:
			if l[-1] == 'B' and l[-2] == 'B':
				l.pop()
				l.pop()
	print(len(l))


t = int(input())
for _ in range(t):
	n = input()
	stack = []
	for i in n:
		if i == 'B' and len(stack) > 0:
			stack.pop()
		else:
			stack.append(i)
	print(len(stack))


def func():
	s = input()
	stack = []
	for i in range(len(s)):
		if len(stack) == 0:
			stack.append(s[i])
		elif s[i] == 'B' and stack[-1] == 'A':
			stack.pop(-1)
		else:
			stack.append(s[i])
	s = ''.join(stack)
	stack = []
	for i in range(len(s)):
		if len(stack) == 0:
			stack.append(s[i])
		elif s[i] == 'B' and stack[-1] == 'B':
			stack.pop(-1)
		else:
			stack.append(s[i])
	return len(stack)
for i in range(int(input())):
	print(func())


def main():
	num_testcases = int(input())
	for _ in range(num_testcases):
		s = input()
		a = 0
		b = 0
		for c in s:
			if c == 'A':
				a += 1
			elif b > 0:
				b -= 1
			elif a > 0:
				a -= 1
			else:
				b += 1
		print(a + b)
main()


import sys, io, os, time
from collections import defaultdict
from collections import Counter
from collections import deque
from itertools import combinations
from itertools import permutations
import bisect, math, heapq
alphabet = 'abcdefghijklmnopqrstuvwxyz'
for ii in range(int(input())):
	s = input()
	stack = [-1]
	for i in range(len(s)):
		if stack[-1] == 'A' and s[i] == 'B':
			stack.pop()
		elif stack[-1] == 'B' and s[i] == 'B':
			stack.pop()
		else:
			stack.append(s[i])
	print(len(stack) - 1)


cases = int(input())
for _ in range(cases):
	s = input()
	if 'B' not in s:
		print(len(s))
	else:
		stack = []
		for char in s:
			if char == 'A':
				stack.append(char)
			elif len(stack) >= 1:
				stack.pop()
			else:
				stack.append(char)
		print(len(stack))


from __future__ import division, print_function
import os, sys
from io import BytesIO, IOBase
if sys.version_info[0] < 3:
	from __builtin__ import xrange as range
	from future_builtins import ascii, filter, hex, map, oct, zip

def ii():
	return int(input())

def si():
	return input()

def mi():
	return map(int, input().strip().split(' '))

def msi():
	return map(str, input().strip().split(' '))

def li():
	return list(mi())

def dmain():
	sys.setrecursionlimit(1000000)
	threading.stack_size(1024000)
	thread = threading.Thread(target=main)
	thread.start()
import sys
input = sys.stdin.readline
scanner = lambda : int(input())
string = lambda : input().rstrip()
get_list = lambda : list(read())
read = lambda : map(int, input().split())
get_float = lambda : map(float, input().split())

def ceil(x):
	if x != int(x):
		x = int(x) + 1
	return x

def factorial(x, m):
	val = 1
	while x > 0:
		val = val * x % m
		x -= 1
	return val

def fact(x):
	val = 1
	while x > 0:
		val *= x
		x -= 1
	return val

def swaparr(arr, a, b):
	temp = arr[a]
	arr[a] = arr[b]
	arr[b] = temp

def gcd(a, b):
	if b == 0:
		return a
	return gcd(b, a % b)

def lcm(a, b):
	return a * b // math.gcd(a, b)

def is_integer(n):
	return math.ceil(n) == math.floor(n)

def nCr(n, k):
	if k > n:
		return 0
	if k > n - k:
		k = n - k
	res = 1
	for i in range(k):
		res = res * (n - i)
		res = res / (i + 1)
	return int(res)

def primefs(n):
	primes = {}
	while n % 2 == 0 and n > 0:
		primes[2] = primes.get(2, 0) + 1
		n = n // 2
	for i in range(3, int(n ** 0.5) + 2, 2):
		while n % i == 0 and n > 0:
			primes[i] = primes.get(i, 0) + 1
			n = n // i
	if n > 2:
		primes[n] = primes.get(n, 0) + 1
	return primes

def power(x, y, p):
	if y == 0:
		return 1
	res = 1
	x = x % p
	if x == 0:
		return 0
	while y > 0:
		if y & 1 == 1:
			res = res * x % p
		y = y >> 1
		x = x * x % p
	return res

def swap(a, b):
	temp = a
	a = b
	b = temp
	return (a, b)

def find(x, link):
	p = x
	while p != link[p]:
		p = link[p]
	while x != p:
		nex = link[x]
		link[x] = p
		x = nex
	return p

def union(x, y, link, size):
	x = find(x, link)
	y = find(y, link)
	if size[x] < size[y]:
		(x, y) = swap(x, y)
	if x != y:
		size[x] += size[y]
		link[y] = x

def sieve(n):
	prime = [True for i in range(n + 1)]
	(prime[0], prime[1]) = (False, False)
	p = 2
	while p * p <= n:
		if prime[p] == True:
			for i in range(p * p, n + 1, p):
				prime[i] = False
		p += 1
	return prime

def phi(n):
	result = n
	p = 2
	while p * p <= n:
		if n % p == 0:
			while n % p == 0:
				n = n // p
			result = result * (1.0 - 1.0 / float(p))
		p = p + 1
	if n > 1:
		result = result * (1.0 - 1.0 / float(n))
	return int(result)

def is_prime(n):
	if n == 0:
		return False
	if n == 1:
		return True
	for i in range(2, int(n ** (1 / 2)) + 1):
		if not n % i:
			return False
	return True

def next_prime(n, primes):
	while primes[n] != True:
		n += 1
	return n
MAXN = int(100000.0 + 5)

def spf_sieve():
	spf[1] = 1
	for i in range(2, MAXN):
		spf[i] = i
	for i in range(4, MAXN, 2):
		spf[i] = 2
	for i in range(3, ceil(MAXN ** 0.5), 2):
		if spf[i] == i:
			for j in range(i * i, MAXN, i):
				if spf[j] == j:
					spf[j] = i
spf = [0 for i in range(MAXN)]

def factoriazation(x):
	res = []
	for i in range(2, int(x ** 0.5) + 1):
		while x % i == 0:
			res.append(i)
			x //= i
	if x != 1:
		res.append(x)
	return res

def factors(n):
	res = []
	for i in range(1, int(n ** 0.5) + 1):
		if n % i == 0:
			res.append(i)
			res.append(n // i)
	return list(set(res))

def int_array():
	return list(map(int, input().strip().split()))

def float_array():
	return list(map(float, input().strip().split()))

def str_array():
	return input().strip().split()

def binary_search(low, high, w, h, n):
	while low < high:
		mid = low + (high - low) // 2
		if check(mid, w, h, n):
			low = mid + 1
		else:
			high = mid
	return low

def check(moves, n):
	val = (moves + 1) // 2
	rem = moves - val
	sol = (val + 1) * (rem + 1)
	return sol < n

def sortSecond(val):
	return val[1]
MOD = int(1000000000.0) + 7
CMOD = 998244353
INF = float('inf')
NINF = -float('inf')
alphs = 'abcdefghijklmnopqrstuvwxyz'
from itertools import permutations
import math
import bisect as bis
import random
import sys
import collections as collect
import functools as fnt
from decimal import Decimal

def solve():
	bomb = string()
	ans = []
	for x in bomb:
		if len(ans) == 0:
			ans.append(x)
		elif x == 'B' and (ans[-1] == 'B' or ans[-1] == 'A'):
			ans.pop()
		else:
			ans.append(x)
	print(len(ans))
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')

def print(*args, **kwargs):
	(sep, file) = (kwargs.pop('sep', ' '), kwargs.pop('file', sys.stdout))
	at_start = True
	for x in args:
		if not at_start:
			file.write(sep)
		file.write(str(x))
		at_start = False
	file.write(kwargs.pop('end', '\n'))
	if kwargs.pop('flush', False):
		file.flush()
if sys.version_info[0] < 3:
	(sys.stdin, sys.stdout) = (FastIO(sys.stdin), FastIO(sys.stdout))
else:
	(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
t = scanner()
for i in range(t):
	solve()


def solve():
	s = input()
	n = len(s)
	(a, b) = (0, 0)
	for i in range(n - 1, -1, -1):
		if s[i] == 'A':
			a += 1
			if b > 0:
				b -= 1
				a -= 1
		else:
			b += 1
	ans = b % 2 + a
	print(ans)
	return

def main():
	t = int(input())
	for i in range(t):
		solve()
	return
main()


tc = int(input())
for t in range(tc):
	s = input()
	count = 0
	for i in s:
		if i == 'A' or count == 0:
			count = count + 1
		else:
			count = count - 1
	print(count)


for _ in range(int(input())):
	s = input()
	l = []
	for c in s:
		if c == 'A':
			l.append(c)
		elif l:
			l.pop()
		else:
			l.append(c)
	print(len(l))


import sys
from sys import stdin, stdout

def get_ints():
	return map(int, sys.stdin.readline().strip().split())
t = int(sys.stdin.readline())
for tt in range(t):
	s = input()
	arr = list()
	for i in s:
		f = 'C'
		if len(arr) != 0:
			f = arr[len(arr) - 1]
		if i == 'B' and f == 'A':
			arr.pop()
			continue
		arr.append(i)
	ans = len(arr)
	cnt = 0
	for i in reversed(arr):
		if i == 'B':
			cnt = cnt + 1
		else:
			cnt = 0
		if cnt == 2:
			ans = ans - 2
			cnt = 0
	print(ans)


for y in range(int(input())):
	lst = list(input())
	n = len(lst)
	mn = 0
	cnta = 0
	cntb = 0
	for i in range(n - 1, -1, -1):
		if lst[i] == 'A':
			if cntb == 0:
				mn += 1
			else:
				cntb -= 1
		else:
			cntb += 1
	if cntb % 2 == 0:
		print(mn)
	else:
		print(1 + mn)


for _ in range(int(input())):
	s = input().strip()
	stack = []
	for i in s:
		if len(stack) == 0 or i == 'A':
			stack.append(i)
		else:
			stack.pop()
	print(len(stack))


for _ in range(int(input())):
	s = input()
	c = 0
	for i in range(len(s)):
		if s[i] == 'A':
			c = c + 1
		if s[i] == 'B':
			if c > 0:
				c = c - 1
			else:
				c = c + 1
	print(c)


for _ in range(int(input())):
	s = input()
	(a, b) = (0, 0)
	for i in s:
		if i == 'A':
			a += 1
		elif a:
			a -= 1
		elif b:
			b -= 1
		else:
			b += 1
	print(a + b)


t = int(input())
for _ in range(t):
	stri = input()
	arr = []
	for i in range(len(stri)):
		if arr and (stri[i] == 'B' and (arr[-1] == 'A' or arr[-1] == 'B')):
			arr.pop()
		else:
			arr.append(stri[i])
	print(len(arr))


T = int(input())
for _ in range(T):
	S = input()
	N = len(S)
	B = 0
	A = 0
	for i in range(N - 1, -1, -1):
		if S[i] == 'B':
			B += 1
		elif B > 0:
			B -= 1
		else:
			A += 1
	ans = A + B % 2
	print(ans)


from os import path
import sys
from heapq import heappush, heappop
from functools import cmp_to_key as ctk
from collections import deque, defaultdict as dd
from bisect import bisect, bisect_left, bisect_right, insort, insort_left, insort_right
from itertools import permutations
from datetime import datetime
from math import ceil, sqrt, log, gcd

def ii():
	return int(input())

def si():
	return input().rstrip()

def mi():
	return map(int, input().split())

def li():
	return list(mi())
abc = 'abcdefghijklmnopqrstuvwxyz'
mod = 998244353
inf = float('inf')
vow = ['a', 'e', 'i', 'o', 'u']
(dx, dy) = ([-1, 1, 0, 0], [0, 0, 1, -1])

def bo(i):
	return ord(i) - ord('a')

def ceil(a, b):
	return (a + b - 1) // b
file = 1

def f():
	sys.stdout.flush()

def solve():
	for _ in range(ii()):
		s = si()
		st = []
		for i in s:
			if len(st) == 0:
				st.append(i)
			elif i == 'B':
				st.pop()
			else:
				st.append(i)
		print(len(st))
if path.exists('input.txt'):
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')
else:
	input = sys.stdin.readline
solve()


for _ in range(int(input())):
	s = input()
	cnt = 0
	ans = 0
	B = 0
	for i in s[::-1]:
		if i == 'B':
			B += 1
			cnt += 1
		elif cnt > 0:
			cnt -= 1
			ans += 1
	ans = 2 * ans + (B - ans) // 2 * 2
	print(len(s) - ans)


num = int(input())
for i in range(num):
	string = input()
	ans = len(string)
	pre = 0
	for j in string:
		if j == 'B' and pre != 0:
			ans -= 2
			pre -= 1
		else:
			pre += 1
	print(ans)


t = int(input())
for i in range(t):
	s = input()
	stack = 0
	for i in range(len(s)):
		if stack == 0 or s[i] == 'A':
			stack += 1
		else:
			stack -= 1
	print(stack)


for _ in range(int(input())):
	inps = input()
	lens = 0
	for i in inps:
		if i == 'B':
			if lens == 0:
				lens += 1
			else:
				lens -= 1
		else:
			lens += 1
	print(lens)


for _ in range(int(input())):
	string = input()
	ans = 0
	for i in string:
		if i == 'B' and ans != 0:
			ans -= 1
		else:
			ans += 1
	print(ans)


t = int(input())
for testix in range(t):
	a = b = 0
	s = input()
	for c in s:
		if c == 'A':
			a += 1
		elif a:
			a -= 1
		else:
			b = b ^ 1
	print(a + b)


t = int(input())
for i in range(t):
	s = str(input())
	count = 0
	for i in range(len(s)):
		if s[i] == 'B' and count != 0:
			count -= 1
		else:
			count += 1
	print(count)


from typing import List

class Stack:

	def __init__(self):
		self.stack: List[str] = []

	def add(self, char: str) -> None:
		self.stack.append(char)

	def remove(self) -> None:
		self.stack.pop()

	def magicAdd(self, char: str) -> None:
		try:
			if char == 'B':
				self.remove()
			else:
				self.add(char)
		except IndexError:
			self.add(char)

	def getLength(self) -> int:
		return len(self.stack)
t: int = int(input())
for i in range(t):
	s = input()
	stack: Stack = Stack()
	for j in range(len(s)):
		stack.magicAdd(s[j])
	print(stack.getLength())


CASES = int(input())
for _ in range(CASES):
	s = input()
	length = len(s)
	extra = 0
	for i in s:
		if i == 'A':
			extra += 1
		elif i == 'B' and extra != 0:
			length -= 2
			extra -= 1
		else:
			extra += 1
	print(extra)


t = int(input())
buf = []
for _ in range(t):
	s = input()
	ans = 0
	rem = 0
	for c in s[::-1]:
		if c == 'B':
			rem += 1
		elif rem == 0:
			ans += 1
		else:
			rem -= 1
	ans += rem % 2
	buf.append(ans)
print('\n'.join(map(str, buf)))


t = int(input())
for i in range(t):
	s = input()
	bcount = 0
	acount = 0
	for si in s[::-1]:
		if si == 'B':
			bcount += 1
		elif bcount == 0:
			acount += 1
		else:
			bcount -= 1
	print(acount + bcount % 2)


t = int(input())
for tt in range(t):
	boom = input()
	eis = [0] * len(boom)
	bs = [0] * len(boom)
	anum = 0
	bnum = 0
	for char in boom:
		if char == 'A':
			anum += 1
		elif anum > 0:
			anum -= 1
		else:
			bnum += 1
	result = anum + bnum % 2
	print(result)


tt = int(input())
for ii in range(tt):
	s = input()
	n = len(s)
	d = 0
	m = 0
	for i in range(n - 1, -1, -1):
		if s[i] == 'A':
			d -= 1
		else:
			d += 1
		m = min(m, d)
	ca = 0
	for i in s:
		if i == 'A':
			ca += 1
	d = ca + m
	cb = n - ca
	cb -= d
	d += cb // 2
	print(n - d * 2)


import sys, io, os
I = lambda : input().encode()
for _ in range(int(I())):
	x = 0
	for c in I().strip():
		if c == ord('A'):
			x += 1
		elif x:
			x -= 1
		else:
			x += 1
	print(x)


import sys
input = sys.stdin.readline

def solve():
	s = input().strip()
	n = ans = len(s)
	st = cnt = 0
	for i in range(n):
		if s[i] == 'A':
			st += 1
		elif st:
			st -= 1
			ans -= 2
		else:
			cnt += 1
	return ans - cnt // 2 * 2
for _ in range(int(input())):
	print(solve())


from itertools import groupby
for _ in range(int(input())):
	s = input()
	grs = [(key, len(list(group))) for (key, group) in groupby(s)]
	balance = 0
	bleft = False
	for (c, nums) in grs:
		if c == 'A':
			balance -= nums
		elif balance < 0:
			if nums > abs(balance):
				bleft = (nums + balance + bleft) % 2
				balance = 0
			else:
				balance += nums
		else:
			assert balance == 0
			bleft = (bleft + nums) % 2
	print(abs(balance) + bleft)


t = int(input())
while t:
	t -= 1
	s = input().strip()
	stack = []
	for c in s:
		if not stack:
			stack.append(c)
		elif c == 'B':
			stack.pop()
		else:
			stack.append(c)
	print(len(stack))


def answer(A):
	n = len(A)
	s = []
	for i in range(n):
		if not s:
			s.append(A[i])
		elif A[i] == 'A':
			s.append('A')
		else:
			s.pop()
	return len(s)
t = int(input())
for i in range(t):
	A = input()
	print(answer(A))


for j in range(int(input())):
	x = input()
	res = 0
	for i in x:
		if i == 'B' and res != 0:
			res -= 1
		else:
			res += 1
	print(res)


import itertools
import math
import sys
from collections import defaultdict

def stdinWrapper():
	data = '3\nAAA\nBABA\nAABBBABBBB\n'
	for line in data.split('\n'):
		yield line
if '--debug' not in sys.argv:

	def stdinWrapper():
		while True:
			yield sys.stdin.readline()
inputs = stdinWrapper()

def inputWrapper():
	return next(inputs)

def readStr():
	if '--debug' in sys.argv:
		return inputWrapper()
	return input()

def getType(_type):
	if _type == str:
		return readStr()
	return _type(inputWrapper())

def getArray(_type):
	return [_type(x) for x in inputWrapper().split()]

def tuplerize(method):

	def wrap(*args, **kwargs):
		res = method(*args, **kwargs)
		if not isinstance(res, (tuple, list)):
			res = (res,)
		return res
	return wrap

@tuplerize
def solve(d):
	stack = 0
	for i in range(len(d)):
		c = d[i]
		if not stack:
			stack += 1
		elif c == 'B':
			stack -= 1
		else:
			stack += 1
	return stack
t = getType(int)
for _ in range(t):
	d = getType(str)
	res = solve(d)
	print(*res)


t = int(input())
for _ in range(t):
	s = input()
	stack = []
	for c in s:
		if len(stack) == 0:
			stack.append(c)
		elif c == 'B' and (stack[-1] == 'A' or stack[-1] == 'B'):
			stack.pop()
		else:
			stack.append(c)
	print(len(stack))


ab = int(input())
for s in range(ab):
	temp = input()
	rem = 0
	for i in temp:
		if i == 'B' and rem != 0:
			rem = rem - 1
		else:
			rem = rem + 1
	print(rem)


gans = []
for _ in range(int(input())):
	s = list(input())
	n = len(s)
	cur = 0
	ans = n
	for i in range(n - 1, -1, -1):
		if s[i] == 'B':
			cur += 1
		elif cur > 0:
			cur -= 1
			ans -= 2
	ans -= cur - cur % 2
	gans.append(ans)
print('\n'.join(map(str, gans)))


import sys
reader = (s.rstrip() for s in sys.stdin)
input = reader.__next__

def gift():
	for _ in range(t):
		aabb = input()
		n = len(aabb)
		ans = n
		curB = 0
		for i in range(n):
			if aabb[n - 1 - i] == 'B':
				curB += 1
			elif curB >= 1:
				ans -= 2
				curB -= 1
		ans -= curB // 2 * 2
		yield ans
t = int(input())
ans = gift()
print(*ans, sep='\n')


for _ in range(int(input())):
	s = input()
	t = []
	for i in range(len(s)):
		if s[i] == 'B' and t and (t[-1] == 'A'):
			t.pop()
		else:
			t.append(s[i])
	if t:
		ans = len(t)
		j = 0
		while j < len(t) - 1:
			if t[j] == 'B' == t[j + 1]:
				ans -= 2
				j += 1
			j += 1
		print(ans)
	else:
		print(0)


from sys import stdin, stdout
import math, bisect
from collections import Counter, deque, defaultdict
L = lambda : list(map(int, stdin.readline().strip().split()))
M = lambda : map(int, stdin.readline().strip().split())
I = lambda : int(stdin.readline().strip())
S = lambda : stdin.readline().strip()
C = lambda : stdin.readline().strip().split()

def pr(a):
	return ' '.join(list(map(str, a)))

def solve():
	s = S()
	a = []
	for i in range(len(s)):
		if a and (a[-1] + s[i] == 'AB' or a[-1] + s[i] == 'BB'):
			a.pop()
		else:
			a += [s[i]]
	print(len(a))
for _ in range(I()):
	solve()


N = int(input())
for _ in range(N):
	s = input()
	ans = 0
	for i in s:
		if i == 'B' and ans != 0:
			ans -= 1
		else:
			ans += 1
	print(ans)


for _ in range(int(input())):
	s = input()
	ns = ''
	for c in s:
		if not ns:
			ns += c
		elif c == 'B':
			ns = ns[:-1]
		else:
			ns += c
	print(len(ns))


import sys
cache = {}

def solve(string):
	counter = 0
	for ele in string:
		if ele == 'B':
			if counter == 0:
				counter += 1
			else:
				counter -= 1
		else:
			counter += 1
	return counter

def readinput():
	tc = int(sys.stdin.readline().rstrip())
	for _ in range(tc):
		string = sys.stdin.readline().rstrip()
		print(solve(string))
readinput()


num = int(input())
while num != 0:
	s = input()
	ans = len(s)
	temp = 0
	for i in s:
		if i == 'B' and temp != 0:
			ans = ans - 2
			temp = temp - 1
		else:
			temp = temp + 1
	num = num - 1
	print(ans)


def solve():
	s = list(input())
	a = 0
	b = 0
	n = len(s)
	ans = 0
	for i in range(n):
		if s[i] == 'A':
			a += 1
		elif a >= 1:
			a -= 1
		else:
			b += 1
	print(a + b % 2)
t = int(input())
for _ in range(t):
	solve()


import time, math as mt, bisect as bs, sys
from sys import stdin, stdout
from collections import deque
from fractions import Fraction
from collections import Counter
from collections import OrderedDict
pi = 3.141592653589793

def II():
	return int(stdin.readline())

def IP():
	return map(int, stdin.readline().split())

def L():
	return list(map(int, stdin.readline().split()))

def P(x):
	return stdout.write(str(x) + '\n')

def PI(x, y):
	return stdout.write(str(x) + ' ' + str(y) + '\n')

def lcm(a, b):
	return a * b // gcd(a, b)

def gcd(a, b):
	if a == 0:
		return b
	elif b == 0:
		return a
	if a > b:
		return gcd(a % b, b)
	else:
		return gcd(a, b % a)

def bfs(adj, v):
	visited = [False] * (v + 1)
	q = deque()
	while q:
		pass

def sieve():
	li = [True] * (2 * 10 ** 5 + 5)
	(li[0], li[1]) = (False, False)
	for i in range(2, len(li), 1):
		if li[i] == True:
			for j in range(i * i, len(li), i):
				li[j] = False
	prime = []
	for i in range(2 * 10 ** 5 + 5):
		if li[i] == True:
			prime.append(i)
	return prime

def setBit(n):
	count = 0
	while n != 0:
		n = n & n - 1
		count += 1
	return count
mx = 10 ** 7
spf = [mx] * (mx + 1)

def SPF():
	spf[1] = 1
	for i in range(2, mx + 1):
		if spf[i] == mx:
			spf[i] = i
			for j in range(i * i, mx + 1, i):
				if i < spf[j]:
					spf[j] = i
	return

def readTree(n, e):
	adj = [set() for i in range(n + 1)]
	for i in range(e):
		(u1, u2) = IP()
		adj[u1].add(u2)
	return adj
mod = 10 ** 9 + 7

def solve():
	s = input()
	n = len(s)
	if n == 1:
		print(1)
		return
	cnta = 0
	for i in range(n):
		if s[i] == 'A':
			cnta += 1
	cntb = 0
	for i in range(n - 1, -1, -1):
		if s[i] == 'B':
			cntb += 1
		elif s[i] == 'A':
			if cntb >= 1 and cnta >= 1:
				cnta -= 1
				cntb -= 1
	if cntb % 2:
		cntb = 1
	else:
		cntb = 0
	print(cnta + cntb)
	return
t = II()
for i in range(t):
	solve()


def solve(s):
	before_a = ''
	amount_of_a = 0
	for let in s:
		if amount_of_a > 0 and let == 'B':
			amount_of_a -= 1
		elif amount_of_a > 0 and let == 'A':
			amount_of_a += 1
		elif amount_of_a == 0 and let == 'B':
			if before_a == 'B':
				before_a = ''
			else:
				before_a = 'B'
		else:
			amount_of_a = 1
	return len(before_a) + amount_of_a
T = int(input())
for _ in range(T):
	s = input()
	print(solve(s))


for i in range(int(input())):
	s = input()
	arr = []
	for e in s:
		if e == 'A':
			arr.append(e)
		elif arr != []:
			arr.pop()
		else:
			arr.append(e)
	print(len(arr))


import sys
input = sys.stdin.readline
for _ in range(int(input())):
	s = input().strip('\n')
	li = [s[0]]
	for i in range(1, len(s)):
		if s[i] == 'B':
			if len(li) > 0:
				li.pop()
			else:
				li.append(s[i])
		else:
			li.append(s[i])
	print(len(li))


for _ in range(int(input())):
	s = input()
	na = 0
	nb = 0
	ans = len(s)
	final = []
	for i in range(len(s)):
		if s[i] == 'A':
			final.append(s[i])
		elif len(final):
			if final[-1] == 'A':
				final.pop()
			else:
				final.append(s[i])
		else:
			final.append(s[i])
	if len(final) <= 1:
		print(len(final))
		continue
	i = 1
	final2 = []
	for i in range(len(final)):
		if final[i] == 'A':
			final2.append(final[i])
		if final[i] == 'B':
			if final2:
				if final2[-1] == 'B':
					final2.pop()
				else:
					final2.append(final[i])
			else:
				final2.append(final[i])
	print(len(final2))


quant_testes = int(input())
for c in range(quant_testes):
	entrada = input()
	ordem = []
	for char in entrada:
		if ordem == []:
			ordem.append(char)
		elif ordem[-1] == 'A' and char == 'B':
			ordem.pop()
		elif ordem[-1] == 'B' and char == 'B':
			ordem.pop()
		else:
			ordem.append(char)
	print(len(ordem))


import re
from collections import deque
T = int(input())
for test in range(T):
	a = input()
	basket = deque(re.findall('A+|B+', a))
	i = 0
	while i < len(basket) - 1:
		if basket[i][0] != 'A':
			i += 1
			continue
		temp = len(basket[i]) - len(basket[i + 1])
		del basket[i]
		del basket[i]
		if temp == 0:
			continue
		elif temp > 0:
			if len(basket) == i:
				basket.append('A' * temp)
			else:
				basket[i] += 'A' * temp
		elif i == 0:
			basket.appendleft('B' * abs(temp))
		else:
			basket[i - 1] += 'B' * abs(temp)
	ans = 0
	for elem in basket:
		if elem[0] == 'B':
			ans += len(elem) % 2
		else:
			ans += len(elem)
	print(ans)


from sys import stdin, stdout
from math import gcd, sqrt, factorial, pi, inf
from collections import deque, defaultdict
input = stdin.readline
R = lambda : map(int, input().split())
I = lambda : int(input())
S = lambda : input().rstrip('\n')
L = lambda : list(R())
P = lambda x: stdout.write(str(x) + '\n')
lcm = lambda x, y: x * y // gcd(x, y)
hg = lambda x, y: (y + x - 1) // x * x
pw = lambda x: 1 if x == 1 else 1 + pw(x // 2)
chk = lambda x: chk(x // 2) if not x % 2 else True if x == 1 else False
sm = lambda x: (x ** 2 + x) // 2
N = 10 ** 6 + 6
for _ in range(I()):
	cnt_a = cnt_b = 0
	for i in S()[::-1]:
		if i == 'B':
			cnt_b += 1
		else:
			cnt_b -= 1
			if cnt_b < 0:
				cnt_a += 1
				cnt_b += 1
	print(cnt_a + cnt_b % 2)


testcases = int(input())
for testcase in range(testcases):
	temparr = input()
	arr = []
	stack = []
	arr1 = []
	stack1 = []
	for i in temparr:
		arr.append(i)
		arr1.append(i)
	for (j, i) in enumerate(arr):
		if len(stack) == 0:
			stack.append(i)
			continue
		if stack[-1] == 'A' and i == 'B':
			stack.pop()
			continue
		stack.append(i)
	for (j, i) in enumerate(arr1):
		if len(stack1) == 0:
			stack1.append(i)
			continue
		if stack1[-1] == 'B' and i == 'B':
			stack1.pop()
			continue
		stack1.append(i)
	arr = stack[:]
	stack = []
	arr1 = stack1[:]
	stack1 = []
	for i in arr:
		if len(stack) == 0:
			stack.append(i)
			continue
		if stack[-1] == 'B' and i == 'B':
			stack.pop()
			continue
		stack.append(i)
	for i in arr1:
		if len(stack1) == 0:
			stack1.append(i)
			continue
		if stack1[-1] == 'B' and i == 'B':
			stack1.pop()
			continue
		stack1.append(i)
	print(min(len(stack), len(stack1)))


t = int(input())
for _ in range(t):
	s = input()[::-1]
	n = len(s)
	a = 0
	b = 0
	ans = 0
	for i in range(n - 1):
		if s[i] == 'A':
			a += 1
			if s[i + 1] == 'B':
				if a <= b:
					b -= a
				else:
					ans += a - b
					b = 0
				a = 0
		else:
			b += 1
	if s[-1] == 'A':
		a += 1
	else:
		b += 1
	if a <= b:
		b -= a
	else:
		ans += a - b
		b = 0
	a = 0
	print(ans + b % 2)


t = int(input())
for you in range(t):
	s = input()
	n = len(s)
	b = 0
	ans = 0
	for i in range(n - 1, -1, -1):
		if s[i] == 'B':
			b += 1
		elif b == 0:
			ans += 1
		else:
			b -= 1
	print(ans + b % 2)


for _ in range(int(input())):
	l = list(input())
	i = 0
	j = 1
	n = len(l)
	if n > 1:
		stack = []
		while j < n:
			if l[i] != 'A' and l[j] != 'B' or (l[i] != 'B' and l[j] != 'B'):
				stack.append(l[i])
				if j == n - 1:
					stack.append(l[j])
				i = i + 1
				j = j + 1
			else:
				j = j + 1
				if len(stack) != 0:
					while len(stack) != 0 and j < n:
						if stack[-1] == 'A' and l[j] == 'B' or (stack[-1] == 'B' and l[j] == 'B'):
							stack.pop()
							j = j + 1
						else:
							if j == n - 1:
								stack.append(l[j])
							break
				elif j == n - 1:
					stack.append(l[j])
				if len(stack) == 0 and j == n - 1:
					stack.append(l[j])
				j = j + 1
				i = j - 1
		print(len(stack))
	else:
		print(n)


from functools import reduce
import os
import sys
from collections import *
from math import *
from bisect import *
from heapq import *
from io import BytesIO, IOBase
input = lambda : sys.stdin.readline().rstrip('\r\n')

def value():
	return tuple(map(int, input().split()))

def arr():
	return [int(i) for i in input().split()]

def sarr():
	return [int(i) for i in input()]

def starr():
	return [str(x) for x in input().split()]

def inn():
	return int(input())

def svalue():
	return tuple(map(str, input().split()))

def parr():
	return [value() for i in range(n)]
mo = 1000000007
inf = 1e+18
div = 998244353
for _ in range(inn()):
	a = input()
	n = len(a)
	i = n - 1
	while i >= 0 and a[i] == 'A':
		i -= 1
	cb = 0
	ca = 0
	ans = 0
	while i >= 0:
		while i >= 0 and a[i] == 'B':
			i -= 1
			cb += 1
		while i >= 0 and a[i] == 'A':
			i -= 1
			ca += 1
		if ca > cb:
			ans += cb * 2
			ca = 0
			cb = 0
		else:
			ans += ca * 2
			cb -= ca
			ca = 0
	val = cb // 2
	ans += val * 2
	print(n - ans)


from bisect import *
from collections import *
from math import *
from heapq import *
from typing import List
from itertools import *
from operator import *
from functools import *
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def RL():
	return map(int, sys.stdin.readline().rstrip().split())

def RLL():
	return list(map(int, sys.stdin.readline().rstrip().split()))

def N():
	return int(input())

@lru_cache(None)
def fact(x):
	if x < 2:
		return 1
	return fact(x - 1) * x

@lru_cache(None)
def per(i, j):
	return fact(i) // fact(i - j)

@lru_cache(None)
def com(i, j):
	return per(i, j) // fact(j)

def linc(f, t, l, r):
	while l < r:
		mid = (l + r) // 2
		if t > f(mid):
			l = mid + 1
		else:
			r = mid
	return l

def rinc(f, t, l, r):
	while l < r:
		mid = (l + r + 1) // 2
		if t < f(mid):
			r = mid - 1
		else:
			l = mid
	return l

def ldec(f, t, l, r):
	while l < r:
		mid = (l + r) // 2
		if t < f(mid):
			l = mid + 1
		else:
			r = mid
	return l

def rdec(f, t, l, r):
	while l < r:
		mid = (l + r + 1) // 2
		if t > f(mid):
			r = mid - 1
		else:
			l = mid
	return l

def isprime(n):
	for i in range(2, int(n ** 0.5) + 1):
		if n % i == 0:
			return False
	return True

def binfun(x):
	c = 1
	res = 0
	for w in arr:
		res += w
		if res > x:
			res = w
		c += 1
	return c

def lowbit(n):
	return n & -n

class BIT:

	def __init__(self, arr):
		self.arr = arr
		self.n = len(arr) - 1

	def update(self, x, v):
		while x <= self.n:
			self.arr[x] += v
			x += x & -x

	def query(self, x):
		ans = 0
		while x:
			ans += self.arr[x]
			x &= x - 1
		return ans

class smt:

	def __init__(self, l, r, arr):
		self.l = l
		self.r = r
		self.value = (1 << 31) - 1 if l < r else arr[l]
		mid = (l + r) // 2
		if l < r:
			self.left = smt(l, mid, arr)
			self.right = smt(mid + 1, r, arr)
			self.value &= self.left.value & self.right.value

	def setvalue(self, x, val):
		if self.l == self.r:
			self.value = val
			return
		mid = (self.l + self.r) // 2
		if x <= mid:
			self.left.setvalue(x, val)
		else:
			self.right.setvalue(x, val)
		self.value = self.left.value & self.right.value

	def ask(self, l, r):
		if l <= self.l and r >= self.r:
			return self.value
		val = (1 << 31) - 1
		mid = (self.l + self.r) // 2
		if l <= mid:
			val &= self.left.ask(l, r)
		if r > mid:
			val &= self.right.ask(l, r)
		return val

class UFS:

	def __init__(self, n):
		self.parent = [i for i in range(n)]
		self.ranks = [0] * n

	def find(self, x):
		if x != self.parent[x]:
			self.parent[x] = self.find(self.parent[x])
		return self.parent[x]

	def union(self, u, v):
		(pu, pv) = (self.find(u), self.find(v))
		if pu == pv:
			return False
		if self.ranks[pu] >= self.ranks[pv]:
			self.parent[pv] = pu
			if self.ranks[pv] == self.ranks[pu]:
				self.ranks[pu] += 1
		else:
			self.parent[pu] = pv

def Prime(n):
	c = 0
	prime = []
	flag = [0] * (n + 1)
	for i in range(2, n + 1):
		if not flag[i]:
			prime.append(i)
			c += 1
		for j in range(c):
			if i * prime[j] > n:
				break
			flag[i * prime[j]] = prime[j]
			if i % prime[j] == 0:
				break
	return prime

def dij(s, graph):
	d = {}
	d[s] = 0
	heap = [(0, s)]
	seen = set()
	while heap:
		(dis, u) = heappop(heap)
		if u in seen:
			continue
		for v in graph[u]:
			if v not in d or d[v] > d[u] + graph[u][v]:
				d[v] = d[u] + graph[u][v]
				heappush(heap, (d[v], v))
	return d
t = N()
for i in range(t):
	s = input()
	res = []
	for (ch, g) in groupby(s):
		res.append((ch, len(list(g))))
	ans = 0
	j = 0
	if res[-1][0] == 'A':
		ans += res[-1][1]
		res.pop()
	flag = 0
	if res and res[0][0] == 'B':
		flag = res[0][1] & 1
		j = 1
	mi = ma = 0
	while j < len(res):
		mi += res[j][1]
		ma += res[j][1]
		if mi >= res[j + 1][1]:
			mi -= res[j + 1][1]
		else:
			mi = mi + res[j + 1][1] & 1
			if mi and flag:
				mi -= 1
				flag = 0
		ma = ma - (res[j + 1][1] & 1)
		j += 2
	ans += mi + flag
	print(ans)


from collections import deque
t = int(input())
for _ in range(t):
	s = input()
	n = len(s)
	stack = deque()
	for i in range(n):
		if s[i] == 'B' and stack:
			stack.pop()
		else:
			stack.append(s[i])
	length = len(stack)
	ans = (stack.count('B') & 1) + stack.count('A')
	print(ans)


def abbb(s):
	if set(s) == {'A'}:
		return len(s)
	j = 1
	l = []
	m = len(s)
	for i in range(m):
		if len(l) == 0:
			l.append(s[i])
		elif s[i] == 'B' and l[-1] == 'A':
			l.pop()
		else:
			l.append(s[i])
	j = 0
	ans = len(l)
	while j < len(l) - 1:
		if l[j] == 'B' and l[j + 1] == 'B':
			ans -= 2
			j += 2
		else:
			j += 1
	return ans
t = int(input())
for _ in range(t):
	s = input()
	print(abbb(s))


from collections import deque
t = int(input())
for _ in range(t):
	s = input()
	q = deque()
	for i in s:
		if i == 'A':
			q.append(i)
		elif len(q) == 0:
			q.append(i)
		else:
			q.popleft()
	print(len(q))


import os
import sys
from math import *
from collections import *
from heapq import *
from bisect import *
from io import BytesIO, IOBase

def vsInput():
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
ALPHA = 'abcdefghijklmnopqrstuvwxyz/'
M = 1000000007
EPS = 1e-06

def Ceil(a, b):
	return a // b + int(a % b > 0)

def value():
	return tuple(map(int, input().split()))

def array():
	return [int(i) for i in input().split()]

def Int():
	return int(input())

def Str():
	return input()

def arrayS():
	return [i for i in input().split()]
for _ in range(Int()):
	s = input()
	ans = 0
	for i in s:
		if i == 'A':
			ans += 1
		elif i == 'B':
			if ans:
				ans -= 1
			else:
				ans += 1
	print(ans)


T = int(input())
for _ in range(T):
	s = input()
	fir = True
	ans = []
	ans.append(s[0])
	n = len(s)
	for i in range(1, n):
		if len(ans) == 0:
			ans.append(s[i])
			continue
		if ans[-1] == 'A' and s[i] == 'B':
			ans.pop()
		elif ans[-1] == 'B' and s[i] == 'B':
			ans.pop()
		else:
			ans.append(s[i])
	print(len(ans))


import sys
from collections import defaultdict
input = sys.stdin.readline
for _ in range(int(input())):
	s = list(input().strip())
	st = []
	for i in s:
		if len(st) == 0:
			st.append(i)
		elif i == 'A':
			st.append(i)
		else:
			st.pop()
	print(len(st))


import sys
input = lambda : sys.stdin.readline().rstrip()
for _ in range(int(input())):
	s = input()
	n = len(s)
	st = []
	dell = 0
	for i in s:
		if i == 'A':
			st.append(i)
		elif st:
			st.pop()
			dell += 2
	n1 = n - dell
	n1 -= len(st)
	print(n - dell - n1 + (n1 & 1))


def process_test_case(i_t):
	s = input()
	stack = []
	for c in s:
		if len(stack) == 0:
			stack.append(c)
		elif c == 'B':
			stack.pop(len(stack) - 1)
		else:
			stack.append(c)
	print(len(stack))
	return None
n_tests = int(input())
for i_test in range(1, n_tests + 1):
	process_test_case(i_test)


for _ in range(int(input())):
	s = input()
	n = len(s)
	b = [[s[0], 1]]
	for i in range(1, n):
		if s[i] == s[i - 1]:
			b[-1][1] += 1
		else:
			b += [[s[i], 1]]
	cnta = 0
	cntb = 0
	if s[0] == 'A':
		cnta = b[0][1]
	else:
		cntb = b[0][1]
	for i in range(1, len(b)):
		if b[i][0] == 'A':
			cnta += b[i][1]
			continue
		if b[i][1] >= cnta:
			cntb += b[i][1] - cnta
			cnta = 0
		else:
			cnta -= b[i][1]
	print(cntb % 2 + cnta)


def bombed(s):
	(i, j) = (0, len(s) - 1)
	t = 0
	q = 0
	while j >= 0:
		if s[j] == 'B':
			t += 1
		elif t > 0:
			t -= 1
		else:
			q += 1
		j -= 1
	return q + t % 2
res = []
for _ in range(int(input())):
	res.append(bombed(input()))
print(*res, sep='\n')


from collections import deque
n = int(input())
while n:
	curr_str = input()
	stack = deque()
	for char in curr_str:
		if char == 'B':
			if len(stack) > 0:
				stack.pop()
			else:
				stack.append(char)
		else:
			stack.append(char)
	n -= 1
	print(len(stack))


t = int(input())
for ii in range(t):
	s = input()
	stack = []
	for i in s:
		if len(stack) == 0:
			stack.append(i)
		elif i == 'B' and stack[-1] == 'A':
			stack.pop(-1)
		elif i == 'B' and stack[-1] == 'B':
			stack.pop(-1)
		else:
			stack.append(i)
	print(len(stack))


t = int(input())
for i in range(0, t):
	s = str(input())
	n = len(s)
	ans = 0
	for j in range(0, n):
		if ans > 0 and s[j] == 'B':
			ans -= 1
		else:
			ans += 1
	print(ans)


import sys
import math
import bisect
import heapq
from bisect import bisect_right
from sys import stdin, stdout

def get_ints_in_variables():
	return map(int, sys.stdin.readline().strip().split())

def get_int():
	return int(sys.stdin.readline())

def get_ints_in_list():
	return list(map(int, sys.stdin.readline().strip().split()))

def get_list_of_list(n):
	return [list(map(int, sys.stdin.readline().strip().split())) for _ in range(n)]

def get_string():
	return sys.stdin.readline().strip()

def Solution(s):
	n = len(s)
	i = 1
	j = 0
	prev = []
	bombs = 0
	while i < n:
		if j == -1 and i < n:
			j = i
			i += 1
		if i == n:
			break
		if s[j] + s[i] == 'AB' or s[j] + s[i] == 'BB':
			i += 1
			if len(prev) != 0:
				j = prev.pop()
			else:
				j = -1
			bombs += 2
		else:
			i += 1
			prev.append(j)
			j += 1
	print(len(s) - bombs)

def main():
	for _ in range(get_int()):
		Solution(get_string())
main()


def ab():
	s = input()
	c = 0
	for i in s:
		if i == 'B' and c != 0:
			c -= 1
		else:
			c += 1
	print(c)
t = int(input())
for i in range(t):
	ab()


for _ in range(int(input())):
	k = list(input())
	n = len(k)
	y = 0
	a = 0
	b = 0
	ans = 0
	for i in range(n - 1, -1, -1):
		if y == 0 and k[i] == 'A':
			ans += 1
		elif y == 0:
			y = 1
			b += 1
		elif k[i] == 'B' and k[i + 1] == 'A':
			if a >= b:
				ans += a - b
				b = 1
				a = 0
			else:
				b += 1 - a
				a = 0
		elif k[i] == 'B':
			b += 1
		else:
			a += 1
	if a == 0:
		if b % 2 == 1:
			print(ans + 1)
		else:
			print(ans)
	elif k == ['A']:
		print(1)
	else:
		ans += max(0, a - b)
		if b > a and (b - a) % 2 == 1:
			ans += 1
		print(ans)


for _ in range(int(input())):
	l = input()
	n = len(l)
	i = 0
	a = 0
	b = 0
	m = 0
	while i < n:
		if l[i] == 'A':
			a += 1
			i += 1
		elif b > 0:
			b = 0
			m += 1
			i += 1
		elif a > 0:
			a -= 1
			m += 1
			i += 1
		else:
			b += 1
			i += 1
	print(n - 2 * m)


for _ in range(int(input())):
	s = input()
	n = len(s)
	stack = [s[0]]
	n_s = len(stack)
	for i in range(1, n):
		if n_s != 0 and ((stack[n_s - 1] == 'A' or stack[n_s - 1] == 'B') and s[i] == 'B'):
			stack.pop()
			n_s = len(stack)
		else:
			stack.append(s[i])
			n_s = len(stack)
	print(n_s)


for _ in range(int(input())):
	s = list(input())
	a = 'A'
	b = 'B'
	stack = []
	for i in s:
		if i == a:
			stack.append(a)
		elif stack == []:
			stack.append(b)
		elif stack[-1] == a or stack[-1] == b:
			stack.pop()
	S = ''
	for i in stack:
		S += i
	print(len(S))


t = int(input())
for _ in range(t):
	s = input()
	n = len(s)
	ans = 0
	bcount = 0
	for i in range(n - 1, -1, -1):
		if s[i] == 'A':
			if bcount == 0:
				ans += 1
			else:
				bcount -= 1
		else:
			bcount += 1
	ans += bcount % 2
	print(ans)


import sys
input = sys.stdin.readlines()

def ABBB(str):
	ans = len(str)
	stack = []
	for char in str:
		stack.append(char)
		while len(stack) > 1 and stack[-1] == 'B':
			ans -= 2
			stack.pop()
			stack.pop()
	return ans
num_test_cases = int(input[0])
test_cases = input[1:]
for case in test_cases:
	print(ABBB(case.strip()))


from sys import stdin, stdout
st = lambda : list(stdin.readline().strip())
li = lambda : list(map(int, stdin.readline().split()))
mp = lambda : map(int, stdin.readline().split())
inp = lambda : int(stdin.readline())
pr = lambda n: stdout.write(str(n) + '\n')
mod = 1000000007

def solve():
	s = st()
	l = []
	n = len(s)
	for i in range(n):
		if l:
			if l[-1] == 'A' and s[i] == 'B':
				l.pop()
			elif l[-1] == 'B' and s[i] == 'B':
				l.pop()
			else:
				l.append(s[i])
		else:
			l.append(s[i])
	pr(len(l))
for _ in range(inp()):
	solve()


for item in [0] * int(input()):
	s = input()
	stack = []
	for i in range(len(s)):
		if s[i] == 'A':
			stack.append(s[i])
		elif len(stack) == 0:
			stack.append('B')
		else:
			stack.pop()
	print(len(stack))


t = int(input())
for T in range(t):
	l = list(input())
	n = len(l)
	ans = 0
	for i in l:
		if i == 'B' and ans != 0:
			ans -= 1
		else:
			ans += 1
	print(ans)


for _ in range(int(input())):
	(s, w) = (input(), 0)
	for i in s:
		if i == 'B' and w != 0:
			w -= 1
		else:
			w += 1
	print(w)


for _ in range(int(input())):
	s = input()
	ans = 0
	for p in s:
		if p == 'B' and ans != 0:
			ans -= 1
		else:
			ans += 1
	print(ans)


for i in range(int(input())):
	s = input()
	(x, y) = (0, 0)
	for j in range(len(s)):
		if s[j] == 'A':
			x += 1
		elif x:
			x -= 1
		elif y:
			y -= 1
		else:
			y += 1
	print(x + y)


for w in range(int(input())):
	s = str(input())
	if s.count('B') == 0:
		print(len(s))
	elif s == 'AB' or s == 'BB':
		print(0)
	else:
		i = 0
		s1 = list(s)
		l = []
		while i < len(s1):
			if len(l) >= 1:
				if s1[i] == 'B' and l[-1] == 'B':
					l.remove(l[-1])
					i += 1
				elif s1[i] == 'B' and l[-1] == 'A':
					l.remove(l[-1])
					i += 1
				else:
					l.append(s1[i])
					i += 1
			else:
				l.append(s1[i])
				i += 1
		print(len(l))


from collections import Counter
import math
import sys
from bisect import bisect, bisect_left, bisect_right
from itertools import permutations

def input():
	return sys.stdin.readline().strip()

def INT():
	return int(input())

def MAP():
	return map(int, input().split())

def LIST(N=None):
	return list(MAP()) if N is None else [INT() for i in range(N)]

def mod():
	return 10 ** 9 + 7
for i in range(INT()):
	s = input()
	n = len(s)
	ans = 0
	ca = 0
	cb = 0
	for i in range(n - 1, -1, -1):
		if s[i] == 'A':
			ca += 1
		if s[i] == 'B':
			cb += 1
		if ca > cb:
			ans += 1
			ca = 0
			cb = 0
		elif ca == cb:
			ca = 0
			cb = 0
		else:
			cb -= ca
			ca = 0
	ans += cb % 2
	print(ans)


import math
teststring = '3\nAAA\nBABA\nAABBBABBBB\n'
online = 'Problem_B' not in __file__
(true, false) = (True, False)
if True:

	def spitout():
		for c in teststring.splitlines():
			yield c
	_ito = spitout()
	if not online:

		def input():
			return next(_ito)

	def build_enum(*a):
		built = dict()
		for (i, c) in enumerate(a):
			built[c] = i
		return lambda x: built[x]
T = int(input())
for ti in range(1, T + 1):
	s = input()
	h = 0
	neg = 0
	for _ in range(len(s)):
		if s[_] == 'A':
			if h < 0:
				neg += h % 2
				h = 0
			h += 1
		else:
			h -= 1
	if h < 0:
		neg -= h
		h = 0
	neg = neg % 2
	ans = h + neg
	print(ans)


from collections import deque, defaultdict
for _ in range(int(input())):
	s = input().strip()
	d = deque()
	i = 0
	while i < len(s):
		if s[i] == 'B':
			try:
				x = d.pop()
			except:
				d.append(s[i])
		else:
			d.append(s[i])
		i += 1
	print(len(d))


t = int(input())
for _ in range(t):
	s = input()
	cnt = 0
	cnt_B = 0
	for char in s:
		if char == 'A':
			cnt -= 1
		else:
			cnt += 1
		if cnt == 1:
			cnt_B += 1
			cnt = 0
	ans = cnt_B % 2
	ans += abs(cnt)
	print(ans)


import io
import os
from collections import Counter, defaultdict, deque

def solve(S):
	stack = []
	for x in S:
		if stack and stack[-1] == 'A' and (x == 'B'):
			stack.pop()
		elif stack and stack[-1] == 'B' and (x == 'B'):
			stack.pop()
		else:
			stack.append(x)
	return len(stack)
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
TC = int(input())
for tc in range(1, TC + 1):
	S = input().decode().rstrip()
	ans = solve(S)
	print(ans)


for _ in range(int(input())):
	s = input()
	n = len(s)
	a = [s[0]]
	c = 0
	for i in s[1:]:
		if i == 'B' and a != []:
			c += 2
			a.pop()
		else:
			a.append(i)
	print(n - c)


from sys import stdin, gettrace
if gettrace():
	inputi = input
else:

	def input():
		return next(stdin)[:-1]

	def inputi():
		return stdin.buffer.readline()

def solve():
	ss = input()
	aexcess = 0
	bs = False
	for s in ss:
		if s == 'A':
			aexcess += 1
		elif aexcess > 0:
			aexcess -= 1
		else:
			bs = not bs
	print(aexcess + (1 if bs else 0))

def main():
	t = int(input())
	for _ in range(t):
		solve()
main()


t = int(input())
while t:
	s = input()
	count = 0
	for i in s:
		count += 1
		if i == 'B' and count > 1:
			count -= 2
	print(count)
	t -= 1


def solve(arr):
	bcount = 0
	length = len(arr)
	for i in range(len(arr) - 1, -1, -1):
		if arr[i] == 'A' and bcount > 0:
			length -= 2
			bcount -= 1
		if arr[i] == 'B':
			bcount += 1
	ans = length - bcount // 2 * 2
	return ans
T = int(input())
for t in range(T):
	arr = list(input())
	ans = solve(arr)
	print(ans)


T = int(input())
for _ in range(T):
	s = input()
	i = 0
	stack = []
	top = -1
	while i < len(s):
		if top < 0 or s[i] == 'A':
			stack.append(s[i])
			top += 1
		else:
			stack.pop()
			top -= 1
		i += 1
	print(len(stack))


rw = int(input())
for wewq in range(rw):
	s = input()
	n = len(s)
	ac = s.count('A')
	bc = s.count('B')
	sufb = []
	sb = 0
	for i in range(n - 1, -1, -1):
		if s[i] == 'B':
			sb += 1
		sufb.append(sb)
	sufb.reverse()
	f = 0
	for i in range(n - 1, -1, -1):
		if s[i] == 'A':
			if sufb[i] > f:
				f += 1
	n -= f * 2
	bc -= f
	ac -= f
	bc = bc % 2
	print(ac + bc)


import sys
for _ in range(int(input())):
	s = input()
	stack = []
	for i in s:
		curr = i
		f = False
		if stack and (stack[-1] == 'A' and curr == 'B' or (stack[-1] == 'B' and curr == 'B')):
			f = True
			stack.pop()
		if f == False:
			stack.append(i)
	print(len(stack))


N = int(input())
for i in range(0, N):
	S = str(input())
	A = 0
	B = 0
	Bstore = 0
	count = len(S)
	for j in range(0, len(S)):
		if S[j] == 'A':
			A += 1
		if S[j] == 'B':
			if A > 0:
				A -= 1
				count -= 2
			elif B == 0:
				B = 1
			else:
				B = 0
				count -= 2
	print(count)


t = int(input())
for i in range(0, t):
	str1 = input()
	x = len(str1)
	ac = 0
	bc = 0
	for j in range(0, x):
		if str1[j] == 'A':
			ac += 1
		else:
			bc += 1
	ans = 0
	if bc == 0:
		ans = x
	elif ac == 0:
		if bc % 2 == 0:
			ans = 0
		else:
			ans = 1
	else:
		bcuh = 0
		nd = 0
		for j in range(x - 1, -1, -1):
			if str1[j] == 'A':
				if bcuh > 0:
					bcuh -= 1
				else:
					nd += 1
			else:
				bcuh += 1
		if bcuh % 2 != 0:
			nd += 1
		ans = nd
	print(ans)


from sys import stdout, stdin
from collections import defaultdict, deque
import math
t = int(stdin.readline())
for _ in range(t):
	s = input()
	d = deque()
	n = len(s)
	for i in range(n):
		if len(d) == 0:
			d.append(s[0])
		elif d[-1] == 'A' and s[i] == 'B':
			d.pop()
		elif d[-1] == 'B' and s[i] == 'B':
			d.pop()
		else:
			d.append(s[i])
	print(len(d))


for _ in range(int(input())):
	s = input()
	list1 = list(s)
	list2 = []
	stack = -1
	for i in range(0, len(s)):
		if list1[i] == 'B':
			if stack != -1:
				stack -= 1
			else:
				stack += 1
		else:
			stack += 1
	print(stack + 1)


t = int(input())
for e in range(t):
	s = input()
	out = 0
	for l in s:
		if out != 0 and l == 'B':
			out -= 1
		else:
			out += 1
	print(out)


t = int(input())
for _ in range(t):
	str = input()
	count = 0
	for s in str:
		if s == 'A' or not count:
			count += 1
		else:
			count -= 1
	print(count)


t = int(input())
for i in range(t):
	s1 = input()
	arr = [s1[0]]
	size = 1
	for i in range(1, len(s1)):
		if s1[i] == 'B' and size > 0:
			arr.pop()
			size -= 1
		else:
			arr.append(s1[i])
			size += 1
	print(size)


import sys
sys.setrecursionlimit(10 ** 5)
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep='\n')

def II():
	return int(sys.stdin.buffer.readline())

def MI():
	return map(int, sys.stdin.buffer.readline().split())

def LI():
	return list(map(int, sys.stdin.buffer.readline().split()))

def LLI(rows_number):
	return [LI() for _ in range(rows_number)]

def BI():
	return sys.stdin.buffer.readline().rstrip()

def SI():
	return sys.stdin.buffer.readline().rstrip().decode()
for _ in range(II()):
	s = SI()
	cb = 0
	ans = len(s)
	for c in s[::-1]:
		if c == 'A':
			if cb:
				ans -= 2
				cb -= 1
		else:
			cb += 1
	ans -= cb // 2 * 2
	print(ans)


from sys import stdin, stdout
test = int(stdin.readline())
for _ in range(test):
	s = stdin.readline().strip()
	stack = []
	for i in s:
		if not len(stack):
			stack.append(i)
		else:
			last = stack.pop()
			if last == 'A' and i == 'B' or (last == 'B' and i == 'B'):
				continue
			else:
				stack.append(last)
				stack.append(i)
	print(len(stack))


t = int(input())
for i in range(t):
	n = input()
	k = 0
	for j in n:
		if j == 'B' and k != 0:
			k -= 1
		else:
			k += 1
	print(k)


for _ in range(int(input())):
	s = input()
	stack = []
	for i in range(len(s)):
		if not stack:
			stack.append(s[i])
		else:
			stack.append(s[i])
			if len(stack) >= 2:
				if stack[-1] == 'B' and stack[-2] == 'A':
					stack.pop()
					stack.pop()
				elif stack[-1] == 'B' and stack[-2] == 'B':
					stack.pop()
					stack.pop()
	print(len(stack))


import math
T = int(input())
for t in range(T):
	a = input()
	d = False
	q = 0
	ans = 0
	for i in a:
		if i == 'A':
			q += 1
		elif q:
			ans += 1
			q -= 1
	bs = a.count('B')
	print(len(a) - 2 * ans - (bs - ans - (bs - ans) % 2))


import bisect
import collections
import copy
import functools
import heapq
import itertools
import math
import random
import re
import sys
import time
import string
sys.setrecursionlimit(99999)
for _ in range(int(input())):
	s = input()
	st = []
	for c in s:
		if c == 'B' and st:
			st.pop()
		else:
			st.append(c)
	print(len(st))


from collections import *
from itertools import *
from bisect import *

def index(a, x):
	i = bisect_left(a, x)
	if i != len(a) and a[i] == x:
		return i
	raise ValueError

def find_lt(a, x):
	i = bisect_left(a, x)
	if i:
		return a[i - 1]
	raise ValueError

def find_le(a, x):
	i = bisect_right(a, x)
	if i:
		return a[i - 1]
	raise ValueError

def find_gt(a, x):
	i = bisect_right(a, x)
	if i != len(a):
		return a[i]
	raise ValueError

def find_ge(a, x):
	i = bisect_left(a, x)
	if i != len(a):
		return a[i]
	raise ValueError

def inp():
	return int(input())

def arrinp():
	return [int(x) for x in input().split()]

def main():
	t = inp()
	for _ in range(t):
		s = input()
		check = set(s)
		if len(check) == 1:
			if check.pop() == 'A':
				print(len(s))
			else:
				x = len(s) % 2
				print(x)
			continue
		left = ''
		(cnt_a, cnt_b) = (0, 0)
		ans = 0
		for j in range(len(s)):
			if s[j] == 'A':
				cnt_a += 1
			else:
				cnt_b += 1
				if cnt_a > 0:
					cnt_a -= 1
					cnt_b -= 1
				else:
					left += 'B'
					cnt_b -= 1
		if len(left) > 0:
			ans += len(left) % 2
		if cnt_a > 0:
			ans += cnt_a
		print(ans)
main()


import sys
input = lambda : sys.stdin.readline().strip()
for _ in range(int(input())):
	s = input()
	l = []
	for i in s:
		if i == 'A':
			l.append(i)
		elif l:
			del l[-1]
		else:
			l.append(i)
	print(len(l))


t = int(input())
for _ in range(t):
	s = input()
	S = []
	for c in s:
		if S:
			t = S[-1] + c
			if t == 'AB':
				S.pop()
				continue
			if t == 'BB':
				S.pop()
				continue
		S.append(c)
	print(len(S))


T = int(input())
for t in range(T):
	a = list(input())
	(d, g) = (0, 0)
	for i in range(len(a) - 1, -1, -1):
		if a[i] == 'B':
			d = d + 1
		if a[i] == 'A':
			if d > 0:
				d = d - 1
			else:
				g = g + 1
	if d % 2 == 1:
		g = g + 1
	print('{}'.format(g))


casen = int(input())
for case in range(casen):
	s = str(input())
	n = len(s)
	bs = 0
	ans = 0
	if n == 1:
		ans = 1
	else:
		for i in range(n - 1, -1, -1):
			if s[i] == 'B':
				bs += 1
			elif bs == 0:
				ans += 1
			else:
				bs -= 1
		if bs % 2 == 1:
			ans += 1
	print(ans)


import sys
input = sys.stdin.readline
for _ in range(int(input())):
	S = list(input())[:-1]
	b = 0
	res = len(S)
	for i in range(len(S) - 1, -1, -1):
		b += S[i] == 'B'
		if S[i] == 'A' and b > 0:
			res -= 2
			b -= 1
	res -= b // 2 * 2
	print(res)


from collections import deque
A = 'A'
B = 'B'

def solve(s):
	stack = deque()
	for c in s:
		if not stack:
			stack.append(c)
		elif c == A:
			stack.append(c)
		else:
			stack.pop()
	return len(stack)
t = int(input())
for i in range(t):
	s = input()
	print(solve(s))


t = int(input())
for _ in range(t):
	s = list(input())
	l = len(s)
	(acnt, bcnt) = (0, 0)
	ans = 0
	for i in range(l - 1, -1, -1):
		if s[i] == 'A':
			acnt += 1
		else:
			bcnt += 1
		ans = max(ans, acnt - bcnt)
	if (l - ans) % 2 == 1:
		ans += 1
	print(ans)


for _ in range(int(input())):
	a = 0
	b = 0
	bb = 0
	s = input()
	for i in range(len(s)):
		if s[i] == 'A':
			if b == 1:
				bb += 1
				b = 0
			a += 1
		if s[i] == 'B':
			if a != 0:
				a -= 1
			else:
				b += 1
				if b % 2 == 0:
					b -= 2
	bb += b
	print(a + bb % 2)


import sys
input = sys.stdin.readline

def main():
	S = input().strip()
	ans = 0
	for s in S:
		if ans == 0:
			ans = 1
		elif s == 'B':
			ans -= 1
		else:
			ans += 1
	print(ans)
for _ in range(int(input())):
	main()


import math
t = int(input())
for _ in range(t):
	arr = list(input())
	n = len(arr)
	stack = []
	for i in range(n):
		if arr[i] == 'A':
			stack.append('A')
		elif len(stack):
			stack.pop(-1)
		else:
			stack.append('B')
	print(len(stack))


for j in range(int(input())):
	r = input()
	s = []
	for i in range(len(r)):
		if r[i] == 'B' and len(s) > 0:
			del s[-1]
		else:
			s.append(r[i])
	print(len(s))


t = int(input())
for i in range(t):
	ar = [str(i) for i in input()]
	n = len(ar)
	a = 0
	b = 0
	for x in range(n):
		if ar[-(x + 1)] == 'A':
			a += 1
			if b > 0:
				b -= 1
				a -= 1
		else:
			b += 1
	b = b % 2
	print(a + b)


t = int(input())
for test in range(t):
	n = input()
	numB = 0
	ans = 0
	for i in range(len(n)):
		if n[len(n) - i - 1] == 'B':
			numB += 1
		elif numB == 0:
			ans += 1
		else:
			numB -= 1
	if numB % 2 == 1:
		ans += 1
	print(ans)


for t in range(int(input())):
	s = [i for i in input()]
	j = len(s) - 1
	i = j - 1
	b = 1
	while b:
		if s[j] == 'B':
			while True:
				if i < 0:
					break
				if s[i] == 'A':
					s[i] = ''
					s[j] = ''
					break
				i -= 1
		j -= 1
		if i > j:
			i = j - 1
		if j < 0 or i < 0:
			b = 0
	aa = 0
	bb = 0
	for i in s:
		if i == 'A':
			aa += 1
		elif i == 'B':
			bb += 1
	print(aa + bb % 2)


def solve():
	s = str(input())
	n = len(s)
	last = [i - 1 for i in range(n)]
	if n == 1:
		print(1)
		return
	i = 1
	ans = n
	while i < n:
		j = last[i]
		if j == -1:
			i += 1
			continue
		if (s[j] == 'A' or s[j] == 'B') and s[i] == 'B':
			ans -= 2
			i += 1
			if i < n:
				last[i] = last[j]
		else:
			i += 1
	print(ans)

def main():
	t = 1
	t = int(input())
	for _ in range(t):
		solve()
main()


import sys
input = sys.stdin.readline

def print(val):
	sys.stdout.write(str(val) + '\n')

def prog():
	for _ in range(int(input())):
		s = list(input().strip())
		a = []
		remove = [0] * len(s)
		num_a = 0
		num_removed = 0
		for i in range(len(s)):
			if s[i] == 'A':
				num_a += 1
				a.append(i)
			elif num_a:
				num_a -= 1
				num_removed += 1
				remove[a.pop()] = 1
				remove[i] = 1
		s2 = []
		for i in range(len(s)):
			if not remove[i]:
				s2.append(s[i])
		s2.append('A')
		b_removed = 0
		curr_b = 0
		for i in range(len(s2)):
			if s2[i] == 'B':
				curr_b += 1
			else:
				b_removed += curr_b // 2
				curr_b = 0
		print(len(s) - (2 * num_removed + 2 * b_removed))
prog()


for t in range(int(input())):
	s = input()
	a = []
	n = len(s)
	for i in range(n):
		if s[i] == 'A' or a == []:
			a.append(s[i])
		else:
			a.pop()
	print(len(a))


import math, sys, os
from collections import defaultdict, deque, OrderedDict, Counter
import bisect as bi
from io import BytesIO, IOBase
mod = 10 ** 9 + 7
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def minp():
	return map(int, sys.stdin.readline().rstrip().split())

def linp():
	return list(map(int, sys.stdin.readline().rstrip().split()))

def inp():
	return int(input())

def print_list(l):
	print(' '.join(map(str, l)))

def BinarySearch(a, x):
	i = bi.bisect_left(a, x)
	if i != len(a) and a[i] == x:
		return i
	else:
		return -1

def gcd(a, b):
	return math.gcd(a, b)

def is_prime(n):
	if n < 5 or n & 1 == 0 or n % 3 == 0:
		return 2 <= n <= 3
	s = (n - 1 & 1 - n).bit_length() - 1
	d = n >> s
	for a in [2, 325, 9375, 28178, 450775, 9780504, 1795265022]:
		p = pow(a, d, n)
		if p == 1 or p == n - 1 or a % n == 0:
			continue
		for _ in range(s):
			p = p * p % n
			if p == n - 1:
				break
		else:
			return False
	return True

def mulinverse(a):
	return pow(a, mod - 2, mod)
for _ in range(inp()):
	s = input()
	n = len(s)
	stack = [s[0]]
	s_len = 1
	for i in range(1, n):
		if s_len != 0 and stack[s_len - 1] == 'A' and (s[i] == 'B'):
			stack.pop()
			s_len -= 1
		else:
			stack.append(s[i])
			s_len += 1
	count_b = 0
	for i in range(s_len):
		if stack[i] == 'A':
			break
		count_b += 1
	if count_b & 1:
		count_b -= 1
		print(s_len - count_b)
	else:
		print(s_len - count_b)


import sys
input = sys.stdin.readline

def main():
	t = int(input())
	for _ in range(t):
		S = input().strip()
		cnt = 0
		acnt = 0
		bcnt = 0
		bprev = 0
		for s in S:
			if s == 'A':
				acnt += 1
			else:
				bcnt += 1
				if acnt > 0:
					tmp = min(acnt, bcnt)
					cnt += tmp
					acnt -= tmp
					bcnt -= tmp
				if acnt == 0:
					bprev += bcnt
					bcnt = 0
		cnt += bprev // 2
		print(len(S) - 2 * cnt)
main()


(_, *inp) = open(0).read().split()
ans = []
for s in inp:
	a = 0
	for c in s:
		a += 1 if c == 'A' or a == 0 else -1
	ans.append(a)
print(*ans, sep='\n')


import sys
(_, *inp) = sys.stdin.readlines()
ans = []
for s in inp:
	a = 0
	for c in s[:-1]:
		a += 1 if c == 'A' or a == 0 else -1
	ans.append(str(a))
sys.stdout.write('\n'.join(ans))


def solve():
	s = input()
	n = len(s)
	acnt = 0
	bcnt = 0
	ans = 0
	for i in s:
		if i == 'B':
			if acnt:
				acnt -= 1
			else:
				bcnt += 1
		if i == 'A':
			acnt += 1
	print(acnt + bcnt % 2)
for i in range(int(input())):
	solve()


ans = []
for _ in range(int(input())):
	a = 0
	for c in input():
		a += 1 if c == 'A' or a == 0 else -1
	ans.append(a)
print(*ans, sep='\n')


import os
import sys
from io import BytesIO, IOBase
import threading
from bisect import bisect_right
from math import gcd, log
from collections import Counter
from pprint import pprint

def main():
	s = input()
	st = []
	for c in s:
		if c == 'A' or len(st) == 0:
			st.append(1)
		else:
			st.pop()
	print(len(st))
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
for _ in range(int(input())):
	main()


from collections import deque
for _ in range(int(input())):
	string = input()
	stack = deque(string[0])
	for i in range(1, len(string)):
		if string[i] == 'B' and stack:
			stack.pop()
		elif string[i] == 'B':
			stack.append('B')
		else:
			stack.append('A')
	print(len(stack))


t = int(input())
for _ in range(t):
	s = input()
	stack = []
	for i in s:
		stack.append(i)
		if len(stack) >= 2:
			g = stack[-2:]
			if g == ['A', 'B'] or g == ['B', 'B']:
				stack.pop()
				stack.pop()
	print(len(stack))


def fn2(i):
	if lis[-1] == i and i == 'B':
		lis.pop()
	elif i == 'B' and lis[-1] == 'A':
		lis.pop()
	else:
		lis.append(i)

def fn3(i):
	lis.append(i)

def fn1(lis, s):
	for i in s:
		if len(lis) > 0:
			fn2(i)
		else:
			fn3(i)
	print(len(lis))
t = int(input())
for tc in range(t):
	s = input()
	lis = []
	fn1(lis, s)


q = int(input())
for _ in range(q):
	s = str(input())
	kek = list()
	(a, b) = (0, 0)
	(A, B) = (0, 0)
	rs = 0
	for i in range(len(s)):
		if s[i] == 'A':
			if b > 0:
				kek.append(b)
				b = 0
			a += 1
			A += 1
		else:
			if a > 0:
				kek.append(a)
				a = 0
			b += 1
			B += 1
	if a > 0:
		kek.append(a)
		a = 0
	if b > 0:
		kek.append(b)
		b = 0
	n = len(kek)
	if s[0] == 'B':
		cnt = 0
		for i in range(1, n - 1, 2):
			cnt += kek[i]
			if cnt <= kek[i + 1]:
				kek[i + 1] -= cnt
				A -= cnt
				B -= cnt
				cnt = 0
			else:
				cnt -= kek[i + 1]
				A -= kek[i + 1]
				B -= kek[i + 1]
	else:
		cnt = 0
		for i in range(0, n - 1, 2):
			cnt += kek[i]
			if cnt <= kek[i + 1]:
				kek[i + 1] -= cnt
				A -= cnt
				B -= cnt
				cnt = 0
			else:
				cnt -= kek[i + 1]
				A -= kek[i + 1]
				B -= kek[i + 1]
	print(A + B % 2)


q = int(input())
for _ in range(q):
	s = input()
	x = 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB'
	y = 'BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB'
	while x in s:
		c = s.replace(x, '')
		s = c
	while y in s:
		c = s.replace(y, '')
		s = c
	while 'AB' in s:
		c = s.replace('AB', '')
		s = c
	while 'BB' in s:
		c = s.replace('BB', '')
		s = c
	print(len(s))


import sys
input = sys.stdin.readline
I = lambda : list(map(int, input().split()))
for tc in range(int(input())):
	s = list(input().strip())
	st = [s[0]]
	for i in s[1:]:
		if st:
			if i == 'B' and s[-1] == 'A':
				st.pop()
			elif i == 'B' and s[-1] == 'B':
				st.pop()
			else:
				st.append(i)
		else:
			st.append(i)
	print(len(st))


for _ in range(int(input())):
	n = input()
	count = 0
	for i in n:
		if i == 'B' and count != 0:
			count = count - 1
		else:
			count = count + 1
	print(count)


def zip_sorted(a, b):
	(a, b) = zip(*sorted(zip(a, b)))
	sorted(zip(a, b), key=lambda x: x[1])
	return (a, b)
t = int(input())
for t1 in range(t):
	s = list(str(input()))
	c = []
	if len(s) > 1:
		for k1 in range(len(s)):
			if k1 == 0:
				a_prev = s[0]
				count = 1
			elif 1 <= k1 <= len(s) - 2:
				if a_prev == s[k1]:
					count = count + 1
				else:
					if a_prev == 'B':
						c.append(count)
					else:
						c.append(-1 * count)
					count = 1
					a_prev = s[k1]
			elif a_prev == s[k1]:
				count = count + 1
				if a_prev == 'B':
					c.append(count)
				else:
					c.append(-1 * count)
			elif a_prev == 'B':
				c.append(count)
				c.append(-1)
			else:
				c.append(-1 * count)
				c.append(1)
	elif s[0] == 'B':
		c.append(1)
	else:
		c.append(-1)
	count = 0
	sum1 = c[len(c) - 1]
	i = len(c) - 1
	if i != 0:
		i = len(c) - 2
		if c[len(c) - 1] >= 0:
			pass
		else:
			count = count + abs(sum1)
			sum1 = 0
		while i >= 0:
			if sum1 + c[i] >= 0:
				sum1 = sum1 + c[i]
			else:
				count = count + abs(sum1 + c[i])
				sum1 = 0
			i = i - 1
		print(abs(sum1) % 2 + count)
	elif sum1 < 0:
		print(abs(sum1))
	else:
		print(abs(sum1) % 2)


n = int(input())
for _ in range(n):
	s = input()
	a = 0
	b = 0
	ab = 0
	bs = 0
	for i in range(len(s)):
		if s[i] == 'A':
			a += 1
		elif s[i] == 'B':
			if a > 0:
				a -= 1
				ab += 1
			else:
				bs += 1
	print(len(s) - 2 * ab - bs // 2 * 2)


from bisect import bisect_left as bl
from bisect import bisect_right as br
from heapq import heappush, heappop
import math
from collections import *
from functools import reduce, cmp_to_key, lru_cache
import io, os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
M = mod = 10 ** 9 + 7

def factors(n):
	return sorted(set(reduce(list.__add__, ([i, n // i] for i in range(1, int(n ** 0.5) + 1) if n % i == 0))))

def inv_mod(n):
	return pow(n, mod - 2, mod)

def li():
	return [int(i) for i in input().rstrip().split()]

def st():
	return str(input().rstrip())[2:-1]

def val():
	return int(input().rstrip())

def li2():
	return [str(i)[2:-1] for i in input().rstrip().split()]

def li3():
	return [int(i) for i in st()]

def give(s):
	l = [[s[0], 1]]
	for i in s[1:]:
		if i == l[-1][0]:
			l[-1][1] += 1
		else:
			l.append([i, 1])
	return l[:]
for _ in range(val()):
	s = st()
	l = give(s)
	ans = 0
	while len(l) > 1:
		node = l.pop()
		if node[0] == 'B':
			node2 = l.pop()
			if node2[1] > node[1]:
				ans += node2[1] - node[1]
			elif node2[1] < node[1]:
				node[1] -= node2[1]
				if len(l):
					l[-1][1] += node[1]
				else:
					l.append(node)
		else:
			ans += node[1]
	if len(l) and l[0][0] == 'B':
		ans += l[0][1] & 1
	elif len(l):
		ans += l[0][1]
	print(ans)


for t in range(int(input())):
	s = input()
	(c, d) = (0, 0)
	for x in s:
		if x == 'A':
			c += 1
		elif c:
			c -= 1
		else:
			d += 1
	ans = c + d % 2
	print(ans)


t = int(input())
for _ in range(t):
	s = str(input())
	n = len(s)
	counta = 0
	countb = 0
	for i in range(n - 1, -1, -1):
		if s[i] == 'A' and countb > 0:
			counta += 1
			countb -= 1
		if s[i] == 'B':
			countb += 1
	x = countb % 2 + s.count('A') - counta
	print(x)


def min_length(s):
	count = 0
	stack = []
	s1 = list(s)
	for i in range(len(s)):
		if s[i] == 'A':
			stack.append(i)
		if s[i] == 'B':
			if len(stack) > 0:
				a = stack.pop()
				count += 1
				s1[a] = 0
				s1[i] = 0
	num_b = len(s) - 2 * count - len(stack)
	count += num_b // 2
	print(len(s) - 2 * count)
t = int(input())
for _ in range(t):
	min_length(input())


import sys
import math
input = sys.stdin.readline

def algo(s):
	ans = 0
	for c in s:
		if c == 'B' and ans != 0:
			ans -= 1
		else:
			ans += 1
	return ans
for _ in range(int(input())):
	string = input().strip()
	res = algo(string)
	print(res)


t = int(input())
for i in range(t):
	s = input()
	res = 0
	for x in s:
		if x == 'A':
			res += 1
		if x == 'B':
			if res > 0:
				res -= 1
			else:
				res += 1
	print(res)


for _ in range(int(input())):
	x = input()
	a = [x[0]]
	for i in range(1, len(x)):
		if x[i] == 'B' and a:
			a.pop()
		else:
			a.append(x[i])
	print(len(a))


t = int(input())
for i in range(t):
	s = input()
	lst = []
	for j in range(len(s)):
		if len(lst) == 0:
			lst.append(s[j])
		elif lst[-1] == 'A' and s[j] == 'B':
			del lst[-1]
		elif lst[-1] == 'B' and s[j] == 'B':
			del lst[-1]
		elif lst[-1] == 'A' and s[j] == 'A':
			lst.append(s[j])
		elif lst[-1] == 'B' and s[j] == 'A':
			lst.append(s[j])
	print(len(lst))


T = int(input())
while T > 0:
	arr = input()
	(count_a, count_b) = (0, 0)
	for i in range(len(arr)):
		if arr[i] == 'A':
			count_a += 1
		elif count_a > 0:
			count_a -= 1
		elif count_b > 0:
			count_b -= 1
		else:
			count_b += 1
	print(count_a + count_b)
	T -= 1


from sys import *
input = lambda : stdin.readline().strip()
listInput = lambda : list(map(int, input().strip().split()))
lineInput = lambda : map(int, input().strip().split())
sJoin = lambda a, sep: f'{sep}'.join(a)
arrJoin = lambda a, sep: f'{sep}'.join(map(str, a))

def isPrime(n):
	if n <= 1:
		return False
	if n <= 3:
		return True
	if n % 2 == 0 or n % 3 == 0:
		return False
	for i in range(5, int(math.sqrt(n) + 1), 6):
		if n % i == 0 or n % (i + 2) == 0:
			return False
	return True

def main():
	for _ in range(int(input())):
		s = input()
		(A, B) = (0, 0)
		for i in s:
			if i == 'A':
				A += 1
			elif i == 'B':
				B += 1
				if A > 0:
					A -= 1
					B -= 1
		B = B % 2
		print(A + B)
main()


for _ in range(int(input())):
	k = 0
	o = 0
	for i in input():
		if i == 'A':
			k += 1
		elif i == 'B' and k > 0:
			k -= 1
		else:
			o += 1
	print(k + o % 2)


TC = int(input())
for i in range(TC):
	s = input()
	ans = 0
	for c in s:
		if c == 'A':
			ans += 1
		elif ans == 0:
			ans += 1
		else:
			ans -= 1
	print(ans)


l = []
for _ in range(int(input())):
	a = list(input())
	n = len(a)
	if len(a) == 1:
		l.append(1)
	else:
		sum = 0
		countb = 0
		for i in range(n - 1, -1, -1):
			if a[i] == 'A':
				if countb == 0:
					sum = sum + 1
				else:
					countb = countb - 1
			else:
				countb = countb + 1
		sum = sum + countb % 2
		l.append(sum)
for i in l:
	print(i)


t = int(input())
for _ in range(t):
	s = str(input())
	acnt = 0
	bcnt = 0
	ans = 0
	for c in s:
		if c == 'B':
			if acnt > 0:
				ans += 2
				acnt -= 1
			elif bcnt > 0:
				ans += 2
				bcnt -= 1
			else:
				bcnt += 1
		elif c == 'A':
			acnt += 1
	print(len(s) - ans)


t = int(input())
while t > 0:
	t -= 1
	s = str(input())
	c = 0
	for i in s:
		if i == 'A':
			c += 1
		elif c > 0:
			c -= 1
		else:
			c += 1
	print(c)


for _ in range(int(input())):
	a = list(input())
	n = len(a)
	c = 1
	mat = []
	q = a[0]
	for i in range(1, n):
		if a[i] == q:
			c += 1
		else:
			mat.append([q, c])
			c = 1
			q = a[i]
	mat.append([q, c])
	c = 0
	c1 = 0
	for i in range(len(mat)):
		if mat[i][0] == 'A':
			c += mat[i][1]
		elif mat[i][0] == 'B' and c != 0:
			m = min(mat[i][1], c)
			mat[i][1] -= m
			c -= m
			c1 += mat[i][1]
		elif mat[i][0] == 'B' and c == 0:
			mat[i][1] = mat[i][1] % 2
			c1 += mat[i][1]
	print(c + c1 % 2)


try:
	t = int(input())
	for i in range(t):
		s = input()
		stack = []
		for i in range(len(s)):
			if len(stack) == 0:
				stack.append(s[i])
			elif s[i] == 'A':
				stack.append('A')
			else:
				stack.pop()
		print(len(stack))
except:
	pass


for _ in range(int(input())):
	s = input()
	a = []
	b = []
	eb = []
	count = 0
	for i in range(len(s)):
		if s[i] == 'A':
			a.append('A')
			if len(a) >= len(b) and len(b) != 0:
				count += 2
				del a[-1]
				del b[-1]
		elif s[i] == 'B':
			if len(a) > len(b):
				b.append('B')
				count += 2
				del a[-1]
				del b[-1]
			else:
				eb.append('B')
	extra = 2 * (len(eb) // 2)
	count += extra
	print(len(s) - count)


import sys
input = sys.stdin.readline
for _ in range(int(input())):
	s = input()[:-1]
	(c, d) = (0, 0)
	for i in s[::-1]:
		if i == 'A':
			if d == 0:
				c += 1
			else:
				d = max(d - 1, 0)
		else:
			d += 1
	if d % 2:
		c += 1
	print(c)


def ques3(s):
	a = 0
	for i in range(len(s)):
		if s[i] == 'B' and a != 0:
			a -= 1
		else:
			a += 1
	print(a)
t = int(input())
for i in range(t):
	s = input()
	ans = ques3(s)
	ans


for i in range(int(input())):
	s = str(input())
	st = []
	for i in range(len(s)):
		if len(st) == 0:
			st.append(s[i])
		elif st[-1] == s[i] and s[i] == 'B':
			st.pop()
		elif st[-1] == 'A' and s[i] == 'B':
			st.pop()
		elif len(st) > 0:
			st.append(s[i])
	print(len(st))


ts = int(input())
for t in range(ts):
	l = input()
	n = len(l)
	out = 0
	bc = 0
	for i in range(n - 1, -1, -1):
		if l[i] == 'B':
			bc += 1
		elif bc > 0:
			bc -= 1
		else:
			out += 1
	print(out + bc % 2)


import sys
from typing import List
sys.setrecursionlimit(10 ** 9)

def lmi():
	return list(map(int, input().split()))

def main():
	t = int(input())
	for _ in range(t):
		s = input()
		result = solve(s)
		print(result)

def solve(S: str) -> int:
	A_count = 0
	B_count = 0
	L = -1
	kukan = []
	for i in range(len(S)):
		if S[i] == 'A':
			A_count += 1
			if A_count == 1:
				L = i
		else:
			B_count += 1
		if A_count < B_count:
			if L != -1:
				kukan.append((L, i))
			L = -1
			A_count = 0
			B_count = 0
	else:
		if L != -1:
			S = S[:L] + 'A' * (A_count - B_count)
	for (l, r) in reversed(kukan):
		S = S[:l] + S[r:]
	return len(S) - S.count('B') // 2 * 2
main()


for t in range(int(input())):
	s = input()
	n = len(s)
	ans = n
	a = 0
	b = 0
	for i in s[::-1]:
		if i == 'B':
			b += 1
		elif b:
			b -= 1
			ans -= 2
	if b:
		d = 2 * (b // 2)
		ans -= d
	print(ans)


import sys
input = sys.stdin.readline

def inp():
	return int(input())

def inlt():
	return list(map(int, input().split()))

def insr():
	s = input()
	return list(s[:len(s) - 1])

def invr():
	return map(int, input().split())
for i in range(inp()):
	b_count = 0
	string = str(input())
	stack = []
	for letter in string:
		if letter == 'A':
			stack.append('A')
		elif letter == 'B' and stack:
			stack.pop()
		elif letter == 'B':
			b_count += 1
	print(len(stack) + b_count % 2)


import sys
readline = sys.stdin.readline
T = int(readline())
Ans = [None] * T
for qu in range(T):
	S = [1 if s == 'A' else 0 for s in readline().strip()]
	stack = []
	for s in S:
		if s:
			stack.append(s)
		elif stack and stack[-1] == 1:
			stack.pop()
		else:
			stack.append(s)
	stack2 = []
	for s in stack:
		if s:
			stack2.append(s)
		elif stack2 and stack2[-1] == 0:
			stack2.pop()
		else:
			stack2.append(s)
	Ans[qu] = len(stack2)
print('\n'.join(map(str, Ans)))


def getlist():
	return list(map(int, input().split()))

def main():
	T = int(input())
	for _ in range(T):
		s = list(input())
		stack = []
		size = 0
		for i in s:
			if i == 'A':
				stack.append('A')
				size += 1
			elif size >= 1:
				stack.pop()
				size -= 1
			else:
				stack.append('B')
				size += 1
		print(size)
main()


length = int(input())
for i in range(length):
	s = input()
	ans = 0
	for i in range(len(s)):
		if s[i] == 'B' and ans != 0:
			ans -= 1
		else:
			ans += 1
	print(ans)


t = int(input())
for i in range(t):
	s = input()
	rjesenje = 0
	for j in s:
		if j == 'B' and rjesenje != 0:
			rjesenje -= 1
		else:
			rjesenje += 1
	print(rjesenje)


import sys
from math import gcd, sqrt, ceil, log2
from collections import defaultdict, Counter, deque
from bisect import bisect_left, bisect_right
import math
from itertools import permutations
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def get_sum(bit, i):
	s = 0
	i += 1
	while i > 0:
		s += bit[i]
		i -= i & -i
	return s

def update(bit, n, i, v):
	i += 1
	while i <= n:
		bit[i] += v
		i += i & -i

def modInverse(b, m):
	g = math.gcd(b, m)
	if g != 1:
		return -1
	else:
		return pow(b, m - 2, m)

def primeFactors(n):
	sa = set()
	sa.add(n)
	while n % 2 == 0:
		sa.add(2)
		n = n // 2
	for i in range(3, int(math.sqrt(n)) + 1, 2):
		while n % i == 0:
			sa.add(i)
			n = n // i
	return sa

def seive(n):
	pri = [True] * (n + 1)
	p = 2
	while p * p <= n:
		if pri[p] == True:
			for i in range(p * p, n + 1, p):
				pri[i] = False
		p += 1
	return pri

def check_prim(n):
	if n < 0:
		return False
	for i in range(2, int(sqrt(n)) + 1):
		if n % i == 0:
			return False
	return True

def debug(l, r):
	maxi = -1
	ans = -1
	for i in range(l, r + 1):
		z = bin(i).count('1')
		if z > maxi:
			maxi = z
			ans = i
	return ans
t = int(input())
for _ in range(t):
	s = list(input())
	n = len(s)
	i = 0
	cnt1 = 0
	cnt2 = 0
	ans = n
	while i < n:
		if s[i] == 'B':
			while i < n and s[i] == 'B':
				cnt1 += 1
				i += 1
		elif s[i] == 'A':
			yo = 0
			while i < n and s[i] == 'A':
				cnt2 += 1
				i += 1
			while i < n and s[i] == 'B':
				yo += 1
				i += 1
			z = min(yo, cnt2)
			ans -= 2 * z
			cnt2 -= z
			yo -= z
			cnt1 += yo
	ans -= cnt1
	if cnt1 % 2 != 0:
		ans += 1
	print(ans)


t = int(input())
for i in range(t):
	l = list(input())
	n = len(l)
	l2 = []
	for i in range(n):
		if len(l2) == 0:
			l2.append(l[i])
		elif len(l2) != 0 and l[i] != 'B':
			l2.append(l[i])
		elif len(l2) != 0 and l[i] == 'B':
			l2.pop()
	print(len(l2))


import sys
import math
import bisect
from sys import stdin, stdout
from math import gcd, floor, sqrt, log
from collections import defaultdict as dd
from bisect import bisect_left as bl, bisect_right as br
from collections import Counter
inp = lambda : int(input())
strng = lambda : input().strip()
jn = lambda x, l: x.join(map(str, l))
strl = lambda : list(input().strip())
mul = lambda : map(int, input().strip().split())
mulf = lambda : map(float, input().strip().split())
seq = lambda : list(map(int, input().strip().split()))
ceil = lambda x: int(x) if x == int(x) else int(x) + 1
ceildiv = lambda x, d: x // d if x % d == 0 else x // d + 1
flush = lambda : stdout.flush()
stdstr = lambda : stdin.readline()
stdint = lambda : int(stdin.readline())
stdpr = lambda x: stdout.write(str(x))
stdarr = lambda : map(int, stdstr().split())
mod = 1000000007
for _ in range(stdint()):
	s = input()
	stack = []
	for i in s:
		if len(stack) == 0:
			stack.append(i)
		elif i == 'B':
			if stack[-1] == 'A' or stack[-1] == 'B':
				stack.pop(-1)
		else:
			stack.append(i)
	print(len(stack))


t = int(input())
q = []
for i in range(t):
	s = str(input())
	l = []
	for c in s:
		if len(l) == 0 or c == 'A':
			l.append(c)
		else:
			l.pop()
	print(len(l))


from sys import stdin, stdout
input = stdin.readline
print = lambda x: stdout.write(str(x) + '\n')
for _ in range(int(input())):
	s = input().strip()
	l = len(s)
	B = 0
	for i in range(len(s) - 1, -1, -1):
		if s[i] == 'A' and B:
			l -= 2
			B -= 1
		elif s[i] == 'B':
			B += 1
	l -= B // 2 * 2
	print(l)


import os

class Node:

	def __init__(self, data, idx):
		self.item = data
		self.next = None
		self.prev = None
		self.idx = idx

	def __str__(self):
		return 'Node %d: %s, %s' % (self.idx, self.item, self.next)

def main():
	test_cases = int(input())
	ans = [None] * test_cases
	for t in range(test_cases):
		s = input()
		if s == '':
			ans[t] = 0
			continue
		head = Node(s[0], 0)
		prev = head
		curr = None
		for i in range(1, len(s)):
			curr = Node(s[i], i)
			prev.next = curr
			curr.prev = prev
			prev = curr
		curr = head
		p = None
		pp = None
		while curr:
			if curr.item == 'B' and p:
				if not pp:
					head = curr.next
					if curr.next:
						curr.next.prev = None
					(pp, p, curr) = (None, None, curr.next)
				else:
					pp.next = curr.next
					if curr.next:
						curr.next.prev = pp
					(pp, p, curr) = (pp.prev, pp, curr.next)
			else:
				(pp, p, curr) = (p, curr, curr.next)
		res = 0
		curr = head
		while curr:
			res += 1
			curr = curr.next
		ans[t] = res
	os.write(1, '\n'.join(map(str, ans)).encode())
main()


def main():
	s = input()
	cur = 0
	for i in range(len(s)):
		if s[i] == 'B' and cur != 0:
			cur -= 1
		else:
			cur += 1
	print(cur)
for _ in range(int(input())):
	main()


import math
import os
import random
import re
import sys

def solve():
	t = int(input())
	for _ in range(t):
		word = str(input())
		answer = 0
		for char in word:
			if char == 'B' and answer != 0:
				answer -= 1
			else:
				answer += 1
		print(answer)
result = solve()


t = int(input())
for i in range(t):
	s = input()
	n = len(s)
	kk = 0
	ans = 0
	for j in range(n):
		if s[j] == 'B':
			if kk > 0:
				ans += 1
				kk -= 1
			else:
				kk += 1
		else:
			kk += 1
	print(n - 2 * ans)


import sys, io, os
Z = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
o = []
for i in range(int(Z())):
	s = Z().strip()
	la = r = 0
	for i in s:
		if i - 65:
			if la:
				la -= 1
			else:
				r += 1
		else:
			la += 1
	o.append(str(la + r % 2))
print('\n'.join(o))


import sys
from collections import deque

def eprint(*args):
	print(*args, file=sys.stderr)
zz = 1
if zz:
	input = sys.stdin.readline
else:
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('all.txt', 'w')
di = [[-1, 0], [1, 0], [0, 1], [0, -1]]

def string(s):
	return ''.join(s)

def fori(n):
	return [fi() for i in range(n)]

def inc(d, c, x=1):
	d[c] = d[c] + x if c in d else x

def bo(i):
	return ord(i) - ord('A')

def li():
	return [int(xx) for xx in input().split()]

def fli():
	return [float(x) for x in input().split()]

def comp(a, b):
	if a > b:
		return 2
	return 2 if a == b else 0

def gi():
	return [xx for xx in input().split()]

def cil(n, m):
	return n // m + int(n % m > 0)

def fi():
	return int(input())

def pro(a):
	return reduce(lambda a, b: a * b, a)

def swap(a, i, j):
	(a[i], a[j]) = (a[j], a[i])

def si():
	return list(input().rstrip())

def mi():
	return map(int, input().split())

def gh():
	sys.stdout.flush()

def isvalid(i, j):
	return 0 <= i < n and 0 <= j < m and (a[i][j] != '.')

def bo(i):
	return ord(i) - ord('a')

def graph(n, m):
	for i in range(m):
		(x, y) = mi()
		a[x].append(y)
		a[y].append(x)
t = fi()
while t > 0:
	t -= 1
	s = si()
	n = len(s)
	st = []
	ans = 0
	for i in range(n):
		if len(st) == 0 or s[i] == 'A':
			st.append(s[i])
		else:
			st.pop()
	print(len(st))


import os, sys, io, math
from tokenize import Triple
from array import array
from math import *
I = lambda : [*map(int, sys.stdin.readline().split())]
IS = lambda : input()
IN = lambda : int(input())
IF = lambda : float(input())
for _ in range(IN()):
	s = IS()
	res = 0
	for i in s:
		if i == 'B' and res != 0:
			res -= 1
		else:
			res += 1
	print(res)


t = int(input())
C = []
for j in range(t):
	s = input()
	nB = 0
	i = 0
	flag = 0
	while i < len(s):
		if s[i] == 'B':
			if flag != 0:
				flag -= 1
			else:
				nB += 1
			i += 1
		else:
			t = i + 1
			flag += 1
			while t < len(s) and s[t] == 'A':
				t += 1
				flag += 1
			i = t
	if flag == 0:
		C.append(nB % 2)
	else:
		C.append(nB % 2 + flag)
for i in range(len(C)):
	print(C[i])


T = int(input())
for _ in range(0, T):
	s = input()
	n = len(s)
	cb = 0
	ans = 0
	for i in range(len(s) - 1, -1, -1):
		if s[i] == 'B':
			cb += 1
		elif cb > 0:
			cb -= 1
			ans += 2
	ans += cb
	if cb % 2 != 0:
		ans -= 1
	print(len(s) - ans)


import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
	s = input().strip()
	out = 0
	for c in s:
		if c == 'B' and out:
			out -= 1
		else:
			out += 1
	print(out)


n = int(input())
for k in range(n):
	c = 0
	a = input()
	for i in range(len(a)):
		if c != 0 and a[i] == 'B':
			c -= 1
		else:
			c += 1
	print(c)


from sys import stdin, stdout
n = int(stdin.readline())
for i in range(n):
	st = stdin.readline()[:-1]
	stack = []
	for i in st:
		if len(stack) == 0:
			stack.append(i)
		elif i == 'B':
			stack.pop()
		else:
			stack.append(i)
	print(len(stack))


import os

class Node:

	def __init__(self, data, idx):
		self.item = data
		self.next = None
		self.prev = None
		self.idx = idx

	def __str__(self):
		return 'Node %d: %s, %s' % (self.idx, self.item, self.next)

def main():
	test_cases = int(input())
	ans = [None] * test_cases
	for t in range(test_cases):
		s = input()
		res = 0
		for c in s:
			if c == 'B' and res > 0:
				res -= 1
			else:
				res += 1
		ans[t] = res
	os.write(1, '\n'.join(map(str, ans)).encode())
main()


from math import *
from sys import *
t = int(stdin.readline())
for _ in range(t):
	a = list(input())
	n = len(a)
	i = 0
	j = 0
	while i < n:
		if a[i] == 'B' and j > 0:
			i += 1
			j -= 1
		else:
			j += 1
			i += 1
	print(j)


for _ in range(int(input())):
	arr = list(input())
	stack = [arr[0]]
	if len(arr) == 1:
		print(1)
	else:
		for i in range(1, len(arr)):
			if arr[i] == 'B' and len(stack) > 0:
				stack.pop()
			else:
				stack.append(arr[i])
		print(len(stack))


x = int(input())
for i in range(0, x):
	n = input()
	d = 0
	for j in n:
		if j == 'B' and d != 0:
			d = d - 1
		else:
			d = d + 1
	print(d)


t = int(input())
while t > 0:
	s = str(input())
	ans = 0
	for i in s:
		if i == 'B' and ans != 0:
			ans = ans - 1
		else:
			ans = ans + 1
	print(ans)
	t = t - 1


t = int(input())
for test in range(t):
	l = []
	s = input()
	for i in range(len(s)):
		if not l:
			l.append(s[i])
		elif l[-1] in ('B', 'A') and s[i] == 'B':
			l.pop()
		else:
			l.append(s[i])
	print(len(l))


t = int(input())
while t > 0:
	s = input()
	l = []
	n = len(s)
	l.append(1)
	for i in range(1, n):
		if s[i] == 'A':
			l.append(l[i - 1] + 1)
		elif s[i] == 'B':
			if l[i - 1] > 0:
				l.append(l[i - 1] - 1)
			else:
				l.append(1)
	print(l[n - 1])
	t -= 1


from collections import defaultdict
import sys
import math
import random

def get_array():
	return list(map(int, sys.stdin.readline().strip().split()))

def get_ints():
	return map(int, sys.stdin.readline().strip().split())

def input():
	return sys.stdin.readline().strip()
for t in range(int(input())):
	s = input()
	n = len(s)
	le = 0
	stack = []
	for i in range(n):
		stack.append(s[i])
		le += 1
		if le >= 2:
			a = stack.pop()
			if a == 'A':
				stack.append('A')
			else:
				stack.pop()
				le -= 2
	print(len(stack))


def abbb(array):
	array = list(array)
	stack = []
	for x in array:
		if not stack:
			stack.append(x)
		elif stack[-1] == 'A' and x == 'B':
			stack.pop()
		elif stack[-1] == 'B' and x == 'B':
			stack.pop()
		else:
			stack.append(x)
	return len(stack)
t = int(input())
final = []
for _ in range(t):
	final.append(abbb(input()))
for _ in range(t):
	print(final[_])


import sys
readline = sys.stdin.readline
t = int(readline())
for _ in range(t):
	s = readline().rstrip()
	ans = len(s)
	b = 0
	for x in s[::-1]:
		if x == 'B':
			b += 1
		elif b:
			b -= 1
			ans -= 2
	if b:
		ans -= b - b % 2
	print(ans)


t = int(input())
for _ in range(t):
	n = str(input())
	l = len(n)
	a = []
	for i in n:
		if i == 'B':
			if len(a) > 0:
				a.pop(len(a) - 1)
			else:
				a.append('B')
		else:
			a.append('B')
	print(len(a))


t = int(input())
for _ in range(t):
	inp = input()
	st = []
	st2 = []
	for l in inp:
		if len(st) == 0:
			st.append(l)
		else:
			lastl = st[-1]
			if lastl + l == 'AB':
				st.pop()
			else:
				st.append(l)
	for l in st:
		if len(st2) == 0:
			st2.append(l)
		else:
			lastl = st2[-1]
			if lastl + l == 'BB':
				st2.pop()
			else:
				st2.append(l)
	print(len(st2))


t = int(input())
for i in range(t):
	ch = input()
	if len(ch) == 0:
		print(0)
		continue
	arr = []
	for c in ch:
		if len(arr) == 0:
			arr.append(c)
		elif c == 'A':
			arr.append(c)
		elif c == 'B':
			if arr[-1] == 'A' or arr[-1] == 'B':
				arr.pop()
			else:
				arr.append(c)
	print(len(arr))


from collections import deque
t = int(input())
for _ in range(t):
	s = input()
	n = len(s)
	stack = deque()
	for i in range(n):
		if s[i] == 'B' and stack:
			stack.pop()
		else:
			stack.append(s[i])
	length = len(stack)
	ans = 0
	if length >= 1:
		temp = []
		(prev, prevIdx) = (stack[0], 0)
		for i in range(1, length):
			if stack[i] != prev:
				temp.append((prev, i - prevIdx))
				prev = stack[i]
				prevIdx = i
		temp.append((prev, length - prevIdx))
		length = len(temp)
		for i in range(length):
			if temp[i][0] == 'B' and temp[i][1] & 1:
				ans += 1
			else:
				ans += temp[i][1]
	print(ans)


import sys
import heapq

class Solution:

	def process(self, S):
		n = len(S)
		stack = []
		for i in range(n):
			skip = 0
			if stack:
				if S[i] != 'A':
					stack.pop()
					skip = 1
					while len(stack) > 2:
						if stack[-1] != 'A':
							stack.pop()
							stack.pop()
						else:
							break
			if not skip:
				stack.append(S[i])
		print(len(stack))

def main():
	lines = sys.stdin.readlines()
	n = int(lines[0])
	for i in range(1, n + 1):
		Solution().process(lines[i].strip())
main()


import re
t = int(input())
while t > 0:
	s = input()
	stack = []
	top = -1
	count = 0
	for i in range(0, len(s)):
		if top == -1:
			stack.append(s[i])
			top += 1
		elif s[i] == 'B':
			stack.remove(stack[top])
			top = top - 1
			count += 1
		else:
			stack.append(s[i])
			top += 1
	print(len(stack))
	t = t - 1


def solve(s):
	not_destroyed = 1
	for i in range(1, len(s)):
		if s[i] == 'B':
			if not_destroyed == 0:
				not_destroyed = 1
				continue
			not_destroyed = max(not_destroyed - 1, 0)
		else:
			not_destroyed += 1
	print(not_destroyed)
t = int(input())
for test in range(t):
	solve(input())

def q_1360_C():

	def solve(n, nums):
		evens = 0
		odds = 0
		for n in nums:
			if n % 2 == 0:
				evens += 1
			else:
				odds += 1
		if evens % 2 == 0 and odds % 2 == 0:
			print('YES')
			return
		if evens % 2 != odds % 2:
			print('NO')
			return
		nums = sorted(nums)
		for i in range(len(nums) - 1):
			if abs(nums[i] - nums[i + 1]) == 1:
				print('YES')
				return
		print('NO')
	t = int(input())
	for test in range(t):
		solve(n=int(input()), nums=[int(w) for w in input().split()])


q = int(input())
for _ in range(q):
	s = input()
	n = len(s)
	cnt = 0
	i = 0
	bbegin = 0
	while i < n and s[i] == 'B':
		bbegin += 1
		i += 1
	a = 0
	b = 0
	while i < n:
		while i < n and s[i] == 'A':
			a += 1
			i += 1
		while i < n and s[i] == 'B':
			b += 1
			i += 1
		if a >= b:
			a -= b
			b = 0
		else:
			b -= a
			a = 0
			bbegin += b
			b = 0
	bbegin %= 2
	cnt = a + bbegin
	print(cnt)


import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def RL():
	return map(int, sys.stdin.readline().rstrip().split())

def RLL():
	return list(map(int, sys.stdin.readline().rstrip().split()))

def N():
	return int(input())

def print_list(l):
	print(' '.join(map(str, l)))
for _ in range(N()):
	s = input()
	(a, b) = (0, 0)
	for c in s:
		if c == 'A':
			a += 1
		elif a > 0:
			a -= 1
		else:
			b += 1
	print(a + (b & 1))


def main():
	s = input()
	ans = 0
	for c in s:
		if c == 'B' and ans > 0:
			ans -= 1
		else:
			ans += 1
	print(ans)
t = int(input())
for _ in range(t):
	main()


def do():
	q = int(input())
	for _ in range(q):
		s = input()
		(cntA, cntB) = (0, 0)
		for i in range(len(s)):
			if s[i] == 'A':
				cntA += 1
			elif cntA > 0:
				cntA -= 1
			else:
				cntB += 1
		print(cntA + cntB % 2)
do()


for s in [*open(0)][1:]:
	(q, w, s) = (0, 0, s.replace('\n', ''))
	for i in s:
		if i == 'A':
			q += 1
		elif q:
			q -= 1
		else:
			w += 1
	print(q + w % 2)


import math
t = int(input())
for w in range(t):
	s = input()
	n = len(s)
	c = 0
	c1 = 0
	for i in range(n - 1, -1, -1):
		if s[i] == 'A':
			if c1 > 0:
				c1 -= 1
				c -= 1
			else:
				c += 1
		else:
			c1 += 1
			c += 1
	print(c - c1 + c1 % 2)


from collections import deque
for t in range(int(input())):
	(s, dq) = (input(), deque())
	for c in s:
		if not dq or c != 'B':
			dq.append(c)
		else:
			dq.pop()
	print(len(dq))


import sys
input = sys.stdin.readline
p = int(input())
for i in range(p):
	st = list(input().strip())
	z = 0
	for i in st:
		if i == 'B' and z != 0:
			z -= 1
		else:
			z += 1
	sys.stdout.write(str(z) + '\n')


for _ in range(int(input())):
	s = input()
	n = len(s)
	s = 'B' + s
	b = 0
	a = 0
	if s[-1] == 'A':
		a += 1
	else:
		b += 1
	r = 0
	for i in range(n - 1, -1, -1):
		if s[i] == 'B' and s[i + 1] == 'A':
			d = min(a, b)
			r += 2 * d
			a = 0
			b -= d
		if i != 0:
			if s[i] == 'A':
				a += 1
			else:
				b += 1
	r += b // 2 * 2
	r = n - r
	print(r)


from collections import deque
from collections import OrderedDict
import math
import sys
import os
import threading
import bisect
import operator
import heapq
from atexit import register
from io import BytesIO
import io
from sys import stdin, stdout
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
input = lambda : sys.stdin.readline().rstrip('\r\n')
for _ in range(int(input())):
	s = input()
	firstA = len(s)
	for i in range(len(s)):
		if s[i] == 'A':
			firstA = i - 1
			break
	answer = 0
	countB = 0
	for i in range(len(s) - 1, firstA, -1):
		if s[i] == 'B':
			countB += 1
		elif countB == 0:
			answer += 1
		else:
			countB -= 1
	countB2 = 0
	for i in range(len(s)):
		if s[i] == 'B':
			countB2 += 1
		else:
			break
	if countB % 2 == 1 and countB2 % 2 == 0:
		answer += 1
	elif countB % 2 == 0 and countB2 % 2 == 1:
		answer += 1
	print(answer)


t = int(input())
while t > 0:
	t -= 1
	s = input()
	l = list(s)
	l2 = []
	for i in l:
		if i == 'A':
			l2.append(i)
		elif i == 'B':
			if len(l2) >= 1:
				l2.remove(l2[-1])
			else:
				l2.append(i)
	print(len(l2))


import collections
for t in range(int(input())):
	s = input()
	if 'B' not in s:
		print(len(s))
	elif 'A' not in s:
		print(1 if len(s) % 2 == 1 else 0)
	else:
		stack = []
		for c in s:
			if not stack:
				stack.append(c)
			elif c == 'A':
				stack.append(c)
			else:
				stack.pop()
		print(len(stack))


import sys, os
from math import sqrt, gcd, ceil, log, floor
from bisect import bisect, bisect_left
from collections import defaultdict, Counter, deque
from heapq import heapify, heappush, heappop
input = sys.stdin.readline
read = lambda : list(map(int, input().strip().split()))
MOD = 998244353

def main():
	ans_ = []
	for _ in range(int(input())):
		s = input().strip()
		stk = []
		for i in s:
			if i == 'B':
				if stk and stk[-1] == 'A':
					stk.pop()
				else:
					stk.append(i)
			else:
				stk.append(i)
		bs = stk.count('B')
		ans = len(stk) - (bs - bs % 2)
		ans_.append(str(ans))
	print('\n'.join(ans_))
main()


def solve(s):
	st = []
	for i in range(len(s)):
		c = s[i]
		if st and st[-1] == 'A' and (c == 'B'):
			st.pop()
		elif st and st[-1] == 'B' and (c == 'B'):
			st.pop()
		else:
			st.append(c)
	return len(st)
t = int(input())
while t:
	s = input()
	print(solve(s))
	t -= 1


def solve(s):
	ans = 0
	hasB = False
	cntA = 0
	for i in range(len(s)):
		if s[i] == 'A':
			cntA += 1
		elif cntA > 0:
			ans += 2
			cntA -= 1
		elif hasB:
			ans += 2
			hasB = False
		else:
			hasB = True
	return len(s) - ans
tests = int(input())
for test in range(tests):
	s = input()
	print(solve(s))


def Zookeeper(A):
	x = []
	for i in A:
		if x == []:
			x.append(i)
		elif x[-1] == 'A' and i == 'B':
			x.pop()
		elif x[-1] == 'B' and i == 'B':
			x.pop()
		else:
			x.append(i)
	return len(x)
for i in range(int(input())):
	S = input()
	print(Zookeeper(S))


for j in range(int(input())):
	s = input()
	stack = [-1]
	a = 0
	b = 0
	pair = 0
	for i in range(len(s)):
		if s[i] == 'A':
			a += 1
		elif a > 0:
			a -= 1
			pair += 2
		elif a == 0:
			b += 1
			if b > 1:
				pair += 2
				b -= 2
	print(len(s) - pair)


import sys
sys.setrecursionlimit(100000)
import math
from collections import Counter, defaultdict, deque

def f(p):
	stack = []
	pos = 0
	while pos < len(p):
		if p[pos] == 'B' and stack != []:
			stack.pop()
		else:
			stack.append(p[pos])
		pos += 1
	return len(stack)
t = int(input())
result = []
for i in range(t):
	p = input()
	result.append(f(p))
for i in range(t):
	print(result[i])


t = int(input())
while t > 0:
	string = input()
	stack = [string[0]]
	for i in range(1, len(string)):
		if len(stack) == 0:
			stack.append(string[i])
		elif stack[-1] + string[i] == 'AB' or stack[-1] + string[i] == 'BB':
			stack.pop()
		else:
			stack.append(string[i])
	print(len(stack))
	t -= 1


(z, zz) = (input, lambda : list(map(int, z().split())))
fast = lambda : stdin.readline().strip()
zzz = lambda : [int(i) for i in fast().split()]
(szz, graph, mod, szzz) = (lambda : sorted(zz()), {}, 10 ** 9 + 7, lambda : sorted(zzz()))
from string import *
from re import *
from collections import *
from queue import *
from sys import *
from collections import *
from math import *
from heapq import *
from itertools import *
from bisect import *
from collections import Counter as cc
from math import factorial as f
from bisect import bisect as bs
from bisect import bisect_left as bsl
from itertools import accumulate as ac

def lcd(xnum1, xnum2):
	return xnum1 * xnum2 // gcd(xnum1, xnum2)

def prime(x):
	p = ceil(x ** 0.5) + 1
	for i in range(2, p):
		if x % i == 0 and x != 2 or x == 0:
			return 0
	return 1

def dfs(u, visit, graph):
	visit[u] = True
	for i in graph[u]:
		if not visit[i]:
			dfs(i, visit, graph)
num = int(z())
for _ in range(num):
	arr = fast()
	ans = 0
	one = 0
	zerr = 0
	for i in arr:
		if i == 'A':
			one += 1
			continue
		if one >= 1:
			one -= 1
			continue
		zerr += 1
		if zerr >= 2:
			zerr -= 2
	print(zerr + one)


import sys
input = sys.stdin.readline
for f in range(int(input())):
	s = input()
	s = s[0:len(s) - 1]
	a = 0
	b = 0
	for c in s:
		if c == 'A':
			a += 1
		elif a > 0:
			a -= 1
		else:
			b += 1
	b %= 2
	print(a + b)


import sys, collections
tc = int(sys.stdin.readline())
for _ in range(tc):
	arr = list(sys.stdin.readline().rstrip())
	n = len(arr)
	st = []
	for i in range(n):
		if arr[i] == 'B':
			if st:
				st.pop()
			else:
				st.append(arr[i])
		else:
			st.append(arr[i])
	print(len(st))


def ii():
	return int(input())

def mi():
	return map(int, input().split())

def li():
	return list(map(int, input().split()))
t = int(input())
for _ in range(t):
	s = str(input())
	l = []
	for i in range(len(s)):
		if l == []:
			l.append(s[i])
		elif s[i] == 'A':
			l.append(s[i])
		elif s[i] == 'B':
			l.pop()
	print(len(l))


def bomb_string(s):
	stack = []
	for c in s:
		if c == 'B' and stack:
			p = stack.pop()
			if p != 'A':
				stack.append(p)
				stack.append(c)
		else:
			stack.append(c)
	new_stack = []
	for c in stack:
		if c == 'B' and new_stack:
			p = new_stack.pop()
			if p != 'B':
				new_stack.append(p)
				new_stack.append(c)
		else:
			new_stack.append(c)
	return len(new_stack)
T = int(input())
for t in range(T):
	print(bomb_string(input()))


import sys
import math
from collections import defaultdict, deque
input = sys.stdin.readline

def inar():
	return [int(el) for el in input().split()]

def main():
	t = int(input())
	for _ in range(t):
		arr = input().strip()
		n = len(arr)
		a = 0
		b = 0
		for i in range(n):
			if arr[i] == 'A':
				a += 1
			elif a > 0:
				a -= 1
			else:
				b += 1
		if b % 2 != 0:
			b = 1
		else:
			b = 0
		print(a + b)
main()


from queue import LifoQueue
for _ in range(int(input())):
	S = input()
	ans = 0
	for _ in S:
		if ans == 0:
			ans += 1
		elif _ == 'A':
			ans += 1
		else:
			ans -= 1
	print(ans)


t = int(input())
while t:
	s = input()
	ans = []
	for val in s:
		if len(ans) > 0 and val == 'B':
			ans.pop()
		else:
			ans.append(val)
	print(len(ans))
	t -= 1


import math
import sys
import collections
import bisect
sys.setrecursionlimit(100000)
input = sys.stdin.readline
flush = sys.stdout.flush
readint = lambda : int(input())
readintm = lambda : map(int, input().strip().split())
readintl = lambda : list(map(int, input().strip().split()))
readfloatm = lambda : map(float, input().strip().split())
readfloatl = lambda : list(map(float, input().strip().split()))
readstr = lambda : input().strip()
readstrl = lambda : list(input().strip())
join = lambda x, l: x.join(map(str, l))
print = lambda *x: sys.stdout.write(' '.join(map(str, x)) + '\n')
printl = lambda l: sys.stdout.write(' '.join(map(str, l)) + '\n')
ceil = lambda x, y: (x + y - 1) // y
mod = 1000000007
for _ in range(readint()):
	s = readstrl()
	ans = 0
	for char in s:
		if char == 'B' and ans:
			ans -= 1
		else:
			ans += 1
	print(ans)


import sys, math
input = sys.stdin.readline
from collections import deque
t = int(input())
for r in range(t):
	s = input().strip('\n')
	stack = deque()
	stack.append(s[0])
	n = len(s)
	count = 1
	for i in range(1, n):
		if s[i] == 'A':
			stack.append(s[i])
			count += 1
		elif count > 0:
			stack.pop()
			count -= 1
		else:
			stack.append(s[i])
			count += 1
	print(count)


mod = 10 ** 9 + 7

def lcm(x, y):
	return x * y / gcd(x, y)

def fact(x, mod=mod):
	ans = 1
	for i in range(1, x + 1):
		ans = ans * i % mod
	return ans

def arr2D(n, m, default=0):
	return [[default for j in range(m)] for i in range(n)]

def arr3D(n, m, r, default=0):
	return [[[default for k in range(r)] for j in range(m)] for i in range(n)]

def sortDictV(x):
	return {k: v for (k, v) in sorted(x.items(), key=lambda item: item[1])}

def solve(lst):
	lst = list(lst)
	lst1 = []
	for i in lst:
		if i == 'A':
			lst1.append('A')
		elif lst1 != [] and lst1[-1] == 'A':
			lst1.pop()
		else:
			lst1.append('B')
	lst2 = []
	for i in lst1:
		if i == 'A':
			lst2.append('A')
		elif lst2 != [] and lst2[-1] == 'B':
			lst2.pop()
		else:
			lst2.append('B')
	return len(lst2)
for a in range(int(input())):
	lst = input()
	print(solve(lst))


for test in range(int(input())):
	s = input()
	na = s.count('A')
	nb = s.count('B')
	res = 0
	pa = s.find('A')
	nb = nb - pa
	r = s[::-1]
	nrb = 0
	for i in reversed(range(len(s))):
		if s[i] == 'B':
			nrb += 1
		elif nrb == 0:
			res += 1
		else:
			nrb -= 1
	if nrb % 2 == 1:
		res += 1
	print(res)


t = int(input())
for i in range(t):
	k = 0
	s = input()
	for j in range(len(s)):
		if k > 0 and s[j] == 'B':
			k -= 1
		else:
			k += 1
	print(k)


def solve():
	S = input()
	cnt = 0
	n_remove = 0
	n_rest = 0
	for (i, c) in enumerate(S):
		if c == 'A':
			cnt += 1
		if c == 'B':
			if cnt > 0:
				cnt -= 1
				n_remove += 1
			else:
				n_rest += 1
	n_rest = n_rest % 2
	return S.count('A') - n_remove + n_rest
TC = int(input())
for _ in range(TC):
	print(solve())


t = int(input())
for _ in range(t):
	s = str(input())
	t = []
	for c in s:
		if c == 'B':
			if t:
				if t[-1] == 'A' or t[-1] == 'B':
					t.pop()
				else:
					t.append(c)
			else:
				t.append(c)
		else:
			t.append(c)
	print(len(t))


t = int(input())
while t > 0:
	t -= 1
	s = input()
	stk = []
	for c in s:
		if c == 'B':
			if len(stk) > 0:
				stk.pop()
			else:
				stk.append(c)
		else:
			stk.append(c)
	print(len(stk))


import sys, os
import heapq, functools, collections
import math, random
from collections import Counter, defaultdict

def solve_(lst):
	c = Counter(lst)
	if c['B'] == 0:
		return len(lst)
	lst = lst[::-1]
	console(lst)
	pairs = 0
	cumulative_B = 0
	for char in lst:
		if char == 'B':
			cumulative_B += 1
		if char == 'A':
			if cumulative_B > 0:
				cumulative_B -= 1
				pairs += 1
	remaining_B = c['B'] - pairs
	res = pairs * 2
	if remaining_B % 2 == 1:
		res += remaining_B - 1
	else:
		res += remaining_B
	return len(lst) - res

def console(*args):
	pass
if os.path.exists('input.txt'):
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')

	def console(*args):
		pass

def solve(*args):
	console('----- solving ------')
	console('----- ------- ------')
	return solve_(*args)
if True:
	inp = iter(sys.stdin.buffer.readlines())
	input = lambda : next(inp)
else:
	input = sys.stdin.buffer.readline
cout = []
for case_num in range(int(input())):
	strr = input()
	strr = [chr(x) for x in strr.strip()]
	res = solve(strr)
	cout.append(res)
print('\n'.join((str(x) for x in cout)))


import sys
input = iter(sys.stdin.read().splitlines()).__next__
t = int(input())
output = []
for _ in range(t):
	s = input()
	queue_a = 0
	queue_b = 0
	matches = 0
	for letter in s:
		if letter == 'A':
			queue_a += 1
		elif letter == 'B':
			if queue_a:
				queue_a -= 1
				matches += 1
			elif queue_b:
				queue_b -= 1
				matches += 1
			else:
				queue_b += 1
	output.append(len(s) - 2 * matches)
print(*output, sep='\n')


t = int(input())
for i in range(t):
	str = input()
	result = 0
	for c in str:
		if c == 'B' and result != 0:
			result -= 1
		else:
			result += 1
	print(result)


t = int(input())
for i in range(t):
	check = True
	s = input()
	c = 0
	for j in s:
		if j == 'B' and c > 0:
			c -= 1
		else:
			c += 1
	print(c)


import sys
from sys import maxsize

def inputint():
	return map(int, sys.stdin.readline().strip().split())

def inputlist():
	return list(map(int, sys.stdin.readline().strip().split()))

def inputstr():
	return list(sys.stdin.readline().strip().split())
for _ in range(int(sys.stdin.readline())):
	s = sys.stdin.readline()
	c = 0
	for i in range(len(s)):
		if s[i] == 'A':
			c = c + 1
		if s[i] == 'B':
			if c > 0:
				c = c - 1
			else:
				c = c + 1
	print(c)


import sys, io, os
BUFSIZE = 8192

class FastIO(io.IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = io.BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(io.IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')

def print(*args, **kwargs):
	(sep, file) = (kwargs.pop('sep', ' '), kwargs.pop('file', sys.stdout))
	at_start = True
	for x in args:
		if not at_start:
			file.write(sep)
		file.write(str(x))
		at_start = False
	file.write(kwargs.pop('end', '\n'))
	if kwargs.pop('flush', False):
		file.flush()
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
T = int(input())
for _ in range(T):
	S = input()
	N = len(S)
	cnt_a = 0
	cnt_b = 0
	n_removed = 0
	for c in S:
		if c == 'A':
			cnt_a += 1
		elif cnt_a > 0:
			cnt_a -= 1
			n_removed += 1
		elif cnt_b == 1:
			cnt_b = 0
			n_removed += 1
		else:
			cnt_b += 1
	ans = N - n_removed * 2
	print(ans)


t = int(input())
for t1 in range(0, t):
	s = input()
	l = []
	for i in range(0, len(s)):
		if len(l) == 0:
			l.append(s[i])
		elif s[i] == 'B':
			if l[-1] == 'B' or l[-1] == 'A':
				l.pop()
			else:
				l.append(s[i])
		else:
			l.append(s[i])
	print(len(l))


n = int(input())
for _ in range(n):
	line = input()
	res = 0
	for c in line:
		if c == 'B' and res > 0:
			res -= 1
		else:
			res += 1
	print(res)


T = int(input())
for _ in range(T):
	s = input()
	n = len(s)
	if s.count('B') == 0:
		print(n)
	else:
		cnt = 0
		l = [s[0]]
		for i in range(1, n):
			if s[i] == 'B' and len(l):
				l.pop()
			else:
				l.append(s[i])
		print(len(l))


t = int(input())
for _ in range(t):
	s = input()
	count = 0
	for c in s:
		if c == 'A':
			count += 1
		elif count == 0:
			count += 1
		else:
			count -= 1
	print(count)


for i in range(int(input())):
	s = input()
	(a_count, b_count) = (0, 0)
	ans = len(s)
	for char in s:
		if char == 'A':
			a_count += 1
		elif a_count > 0:
			ans -= 2
			a_count -= 1
		else:
			b_count += 1
	if b_count % 2 == 0:
		ans -= b_count
	else:
		ans -= b_count - 1
	print(ans)


for _ in range(int(input())):
	s = input()
	st = []
	l = 0
	n = len(s)
	for i in range(n):
		if l == 0:
			st.append(s[i])
			l += 1
		elif st[-1] == 'A' and s[i] == 'B':
			st.pop()
			l -= 1
		elif st[-1] == 'B' and s[i] == 'B':
			st.pop()
			l -= 1
		else:
			st.append(s[i])
			l += 1
	print(l)


t = int(input())
for _ in range(t):
	s = list(input())
	cntA = cntB = 0
	for i in range(len(s)):
		if s.pop() == 'A':
			cntA += 1
			if cntB > 0:
				cntB -= 1
				cntA -= 1
		else:
			cntB += 1
	ans = cntB % 2 + cntA
	print(ans)


import sys
input = sys.stdin.readline
for _ in range(int(input())):
	s = []
	for char in input().rstrip():
		if char == 'B':
			if s:
				s.pop()
				continue
		s.append(char)
	print(len(s))


for _ in range(int(input())):
	l = list(input())
	ac = l.count('A')
	bc = l.count('B')
	idx = 0
	n = len(l)
	s = 0
	prev = 0
	m = 0
	temp = 0
	for i in range(n):
		if l[i] == 'A':
			if s < 0:
				temp += abs(s)
				s = 0
			prev = s
			s += 1
		elif l[i] == 'B':
			prev = s
			s -= 1
		if s >= 0 and prev > s:
			m += 2
	if s < 0:
		temp += abs(s)
	if temp > 0:
		if temp % 2 == 0:
			m += temp
		else:
			m += temp - 1
	print(abs(n - m))


import bisect

def solve(s):
	n = len(s)
	stack = []
	for j in range(n):
		if stack:
			if s[j] == 'B':
				stack.pop()
			else:
				stack.append('A')
		else:
			stack.append(s[j])
	return len(stack)
t = int(input())
ans = []
for i in range(t):
	s = list(input())
	ans.append(solve(s))
for test in ans:
	print(test)


for _ in range(int(input())):
	s = input()
	ca = 0
	cb = 0
	for i in s:
		if i == 'A':
			ca += 1
		elif ca != 0:
			ca -= 1
		elif cb == 0 and ca == 0:
			cb += 1
		elif cb != 0 and ca == 0:
			cb -= 1
	print(ca + cb)


t = int(input())
for _ in range(t):
	s = input()
	A = []
	for x in s:
		if A:
			if x == 'B':
				A.pop()
			else:
				A.append(x)
		else:
			A.append(x)
	print(len(A))


for _ in range(int(input())):
	(text, ans) = (str(input()), 0)
	for i in text:
		if i == 'B' and ans != 0:
			ans -= 1
		else:
			ans += 1
	print(ans)


t = int(input())
while t:
	a = input()
	ans = 0
	for i in a:
		if i == 'B' and ans != 0:
			ans = ans - 1
		else:
			ans = ans + 1
	print(ans)
	t = t - 1


n = int(input())
for i in range(n):
	s = str(input())
	c = 0
	for j in s:
		if c == 0 or j == 'A':
			c += 1
		else:
			c -= 1
	print(c)


from collections import *
import sys

def ri():
	return int(input())

def rl():
	return list(map(int, input().split()))
t = ri()
for _ in range(t):
	ss = input()
	if len(ss) == 1:
		print(1)
		continue
	new = []
	n = len(ss)
	current_n = 1
	current = ss[0]
	for i in range(1, n):
		if ss[i] == current:
			current_n += 1
		else:
			new.append(current_n)
			current_n = 1
			current = ss[i]
	new.append(current_n)
	letter = ss[-1]
	ans = 0
	if letter == 'A':
		ans += new.pop()
	while new:
		b = new.pop()
		if not new:
			ans += b % 2
		else:
			a = new.pop()
			if a > b:
				ans += a - b
			else:
				b -= a
				if not new:
					ans += b % 2
				else:
					new[-1] += b
	print(ans)


import sys
input = sys.stdin.readline
for _ in range(int(input())):
	s = input().strip()
	d = {'A': 0, 'B': 0}
	for i in range(len(s)):
		if s[i] == 'B':
			if d['A'] > 0:
				d['A'] -= 1
				d['B'] -= 1
			if d['B'] > 0:
				d['B'] -= 2
		d[s[i]] += 1
	print(d['A'] + d['B'])


num = int(input())
for _ in range(num):
	word = input()
	l = []
	for i in word:
		if i == 'B' and len(l) != 0:
			l.pop()
		else:
			l.append(i)
	print(len(l))


import sys
import math, bisect
sys.setrecursionlimit(10 ** 6)
from itertools import groupby, accumulate
from heapq import heapify, heappop, heappush
from collections import deque, Counter, defaultdict

def I():
	return int(sys.stdin.readline())

def neo():
	return map(int, sys.stdin.readline().split())

def Neo():
	return list(map(int, sys.stdin.readline().split()))
for _ in range(I()):
	s = input()
	st = ['a']
	for i in s:
		if i == 'B' and st[-1] in 'AB':
			st.pop()
		else:
			st.append(i)
	print(len(st) - 1)


import sys
t = int(input().strip())
for a0 in range(t):
	n = input()
	count = 0
	for i in n:
		if count != 0 and i == 'B':
			count -= 1
		else:
			count += 1
	print(count)


def what(s):
	ans = 0
	for c in s:
		if c == 'B':
			if ans > 0:
				ans -= 1
			else:
				ans += 1
		else:
			ans += 1
	return ans
t = int(input())
for _ in range(t):
	s = input()
	print(what(s))


from sys import stdin

class Input:

	def __init__(self):
		self.it = iter(stdin.readlines())

	def line(self):
		return next(self.it).strip()

	def array(self, sep=' ', cast=int):
		return list(map(cast, self.line().split(sep=sep)))

def testcases(unknown=False):
	inpt = Input()

	def testcases_decorator(func):
		(cases,) = [float('Inf')] if unknown else inpt.array()
		while cases > 0:
			try:
				func(inpt)
				cases -= 1
			except StopIteration:
				break
	return testcases_decorator

@testcases()
def solve(inpt):
	s = inpt.line()
	tp = 0
	for c in s:
		if tp and c == 'B':
			tp -= 1
		else:
			tp += 1
	print(tp)


from math import *
t = int(input())
while t:
	t = t - 1
	s = input()
	aa = 0
	bb = 0
	for i in s:
		if i == 'A':
			aa += 1
		elif i == 'B' and aa != 0:
			aa -= 1
		else:
			bb += 1
	print(bb % 2 + aa)


for t in range(int(input())):
	s = input()
	s = s[::-1]
	count = 0
	add = 0
	for i in s:
		if i == 'A':
			count -= 1
		else:
			count += 1
		if count < 0:
			add += 1
			count = 0
	if count > 0 and count % 2 == 1:
		add += 1
	print(add)


for _ in range(int(input())):
	stack = []
	s = input()
	length = 0
	for char in s:
		if len(stack) == 0:
			stack.append(char)
			length += 1
			continue
		last = stack[-1]
		if last + char in ['AB', 'BB']:
			stack.pop()
			length -= 1
		else:
			stack.append(char)
			length += 1
	print(length)


def boom(string):
	min_len = 0
	count = 0
	Index_of_last_A_banned = len(string)
	for i in range(len(string) - 1, -1, -1):
		if string[i] == 'A':
			if count <= 0:
				min_len += 1
				count = 0
				Index_of_last_A_banned = i
			else:
				count -= 1
		else:
			count += 1
	if (string[:Index_of_last_A_banned].count('B') - string[:Index_of_last_A_banned].count('A')) % 2 == 1:
		min_len += 1
	return min_len
t = int(input())
for i in range(t):
	print(boom(input()))


import sys
input = sys.stdin.readline
t = int(input())
for i in range(t):
	s = input().rstrip()
	k = s[::-1]
	ans = 0
	cum = 0
	for i in k:
		if i == 'A':
			cum += 1
		if i == 'B':
			cum -= 1
		if cum > ans:
			ans = cum
	r = len(s) - ans
	ans += r % 2
	print(ans)


def testcase():
	s = input()
	n = len(s)
	stack = []
	for ch in s:
		if ch == 'A' or len(stack) == 0:
			stack.append('A')
		else:
			stack.pop()
	print(len(stack))
	return
t = int(input())
for _ in range(t):
	testcase()


for _ in range(int(input())):
	s = list(input())
	count = 0
	res = []
	for i in range(len(s)):
		if len(res) > 0:
			if res[len(res) - 1] == 'B' and s[i] == 'B':
				res.pop()
				count += 2
			elif res[len(res) - 1] == 'A' and s[i] == 'B':
				res.pop()
				count += 2
			else:
				res.append(s[i])
		else:
			res.append(s[i])
	print(len(s) - count)


import sys
from collections import defaultdict as dd
from collections import Counter as cc
from queue import Queue
import math
import itertools
try:
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')
except:
	pass
for _ in range(int(input())):
	q = input()[::-1]
	i = 0
	w = len(q)
	while i < w and q[i] == 'A':
		i += 1
	e = i
	r = 0
	t = e
	while i < w:
		if q[i] == 'B':
			r += 1
		elif r > 0:
			r -= 1
		else:
			t += 1
		i += 1
	if r % 2 == 0:
		print(t)
	else:
		print(t + 1)


tests = int(input())
for _ in range(tests):
	s = input()
	res = 0
	q = []
	for c in s:
		if not q or c == 'A':
			q.append(c)
		elif q:
			res += 2
			del q[-1]
		else:
			q.append(c)
	print(len(s) - res)


from collections import Counter, OrderedDict
from itertools import permutations as perm
from collections import deque
from sys import stdin
from bisect import *
from heapq import *
import math
g = lambda : stdin.readline().strip()
gl = lambda : g().split()
gil = lambda : [int(var) for var in gl()]
gfl = lambda : [float(var) for var in gl()]
gcl = lambda : list(g())
gbs = lambda : [int(var) for var in g()]
mod = int(1000000000.0) + 7
inf = float('inf')
(t,) = gil()
for _ in range(t):
	s = g()
	n = len(s)
	stack = []
	rem = 0
	for ch in s:
		if stack:
			if ch == 'B' and stack[-1] == 'A':
				rem += 2
				stack.pop()
			else:
				stack.append(ch)
		else:
			stack.append(ch)
	b = stack.count('B')
	add = b - (b & 1)
	print(n - (rem + add))


import os
from io import BytesIO, IOBase
import sys
from collections import defaultdict, deque, Counter
from bisect import *
from math import sqrt, pi, ceil
import math
from itertools import permutations
from copy import deepcopy

def main():
	for t in range(int(input())):
		a = input().rstrip()
		n = len(a)
		if n == 1:
			print(1)
			continue
		f = []
		b = []
		for i in range(n):
			if a[i] == 'A':
				f.append(i)
			elif f != []:
				f.pop()
			elif b != []:
				b.pop()
			else:
				b.append(i)
		print(len(f) + len(b))
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


for _ in range(int(input())):
	s = input()
	a = []
	for i in range(len(s)):
		if s[i] == 'A':
			a.append('A')
		elif len(a) != 0:
			a.pop()
		else:
			a.append('B')
	print(len(a))


t = int(input())
for i in range(t):
	string = input()
	stack = []
	b_count = 0
	for char in string:
		if char == 'A':
			stack.append('A')
		elif len(stack) == 0:
			b_count += 1
		else:
			stack.pop()
	print(len(stack) + b_count % 2)


t = int(input())
for i in range(t):
	L = input()
	a = 0
	b = 0
	tot = 0
	for i in L:
		if i == 'A':
			a += 1
		if i == 'B':
			if a > 0:
				tot += 2
				a -= 1
			else:
				b += 1
	print(len(L) - tot - b // 2 * 2)


for _ in range(int(input())):
	l = list(input())
	c = 0
	for x in l:
		if x == 'B' and c != 0:
			c -= 1
		else:
			c += 1
	print(c)


from math import *
from collections import deque
from copy import deepcopy
import sys

def inp():
	return sys.stdin.readline().rstrip('\r\n')

def multi():
	return map(int, input().split())

def strmulti():
	return map(str, inp().split())

def lis():
	return list(map(int, inp().split()))

def lcm(a, b):
	return a * b // gcd(a, b)

def ncr(n, r):
	return factorial(n) // (factorial(r) * factorial(max(n - r, 1)))

def stringlis():
	return list(map(str, inp().split()))

def out(var):
	sys.stdout.write(str(var))

def printlist(a):
	print(' '.join((str(a[i]) for i in range(len(a)))))

def isPrime(n):
	if n <= 1:
		return False
	if n <= 3:
		return True
	if n % 2 == 0 or n % 3 == 0:
		return False
	i = 5
	while i * i <= n:
		if n % i == 0 or n % (i + 2) == 0:
			return False
		i = i + 6
	return True
t = int(input())
for _ in range(t):
	s = inp()
	a = deque([])
	for i in s:
		if i == 'A':
			a.append(i)
		elif len(a) != 0:
			a.pop()
		else:
			a.append(i)
	print(len(a))


t = int(input())
while t:
	t -= 1
	s = input()
	stack = [s[0]]
	for i in range(1, len(s)):
		if len(stack) > 0 and (stack[-1] == 'A' and s[i] == 'B' or (stack[-1] == 'B' and s[i] == 'B')):
			stack.pop()
			while len(stack) > 2 and (stack[-2:] == 'AB' or stack[-2:] == 'BB'):
				stack.pop()
				stack.pop()
		else:
			stack.append(s[i])
	print(len(stack))


a = int(input())
for i in range(0, a):
	s = input()
	arr = []
	for i in s:
		if i == 'A':
			arr.append(0)
		else:
			arr.append(1)
	a = 0
	b = 0
	summ = 0
	for i in arr:
		if i == 0:
			a = a + 1
		if i == 1:
			b = b + 1
			if a > 0:
				a = a - 1
				b = b - 1
				summ = summ + 2
			elif b > 1:
				b = b - 2
				summ = summ + 2
	print(len(arr) - summ)


import sys

def rs():
	return sys.stdin.readline().rstrip()

def ri():
	return int(sys.stdin.readline())

def ria():
	return list(map(int, sys.stdin.readline().split()))

def ws(s):
	sys.stdout.write(s + '\n')

def wi(n):
	sys.stdout.write(str(n) + '\n')

def wia(a):
	sys.stdout.write(' '.join([str(x) for x in a]) + '\n')
import math
from collections import defaultdict
for _ in range(ri()):
	s = rs()
	x = s[0]
	for i in range(1, len(s)):
		if len(x) > 0 and x[-1] == 'A' and (s[i] == 'B'):
			x = x[:-1]
		elif len(x) > 0 and s[i] == 'B' and (x[-1] == 'B'):
			x = x[:-1]
		else:
			x += s[i]
	wi(len(x))


from itertools import groupby
for _ in [0] * int(input()):
	s = input()
	c = 0
	for i in s:
		if i == 'A':
			c += 1
		elif c:
			c -= 1
		else:
			c += 1
	print(c)


for t in range(int(input())):
	string = list(input())
	stack = []
	stack.append(string[0])
	for i in range(1, len(string)):
		ele = string[i]
		if ele == 'A':
			stack.append('A')
		elif len(stack) == 0:
			stack.append('B')
		else:
			stack.pop(-1)
	print(len(stack))


t = int(input())
for i in range(t):
	s = input()
	b = []
	for j in s:
		b.append(j)
	n = len(b)
	j = 0
	ans = 0
	res = []
	while j < n:
		if res == []:
			res.append(b[j])
		elif b[j] == 'B':
			res.pop()
		else:
			res.append(b[j])
		j += 1
	print(len(res))


import sys, math
import io, os
from bisect import bisect_left as bl, bisect_right as br, insort
from heapq import heapify, heappush, heappop
from collections import defaultdict as dd, deque, Counter

def data():
	return sys.stdin.readline().strip()

def mdata():
	return list(map(int, data().split()))

def outl(var):
	sys.stdout.write('\n'.join(map(str, var)) + '\n')

def out(var):
	sys.stdout.write(str(var) + '\n')
INF = float('inf')
mod = 10 ** 9 + 7
for t in range(int(data())):
	s = data()
	stack = []
	for i in s:
		if stack and i == 'B':
			stack.pop()
		else:
			stack.append(i)
	out(len(stack))


for _ in range(int(input())):
	arr = list(input())
	stck = []
	if len(arr) == 1:
		print(1)
	else:
		for x in arr:
			if x == 'B' and len(stck) > 0:
				stck.pop()
			else:
				stck.append(x)
		print(len(stck))


t = int(input())
while t:
	s = input()
	c = 1
	for x in range(1, len(s)):
		if s[x] == 'B' and c > 0:
			c -= 1
		else:
			c += 1
	print(c)
	t -= 1


import collections
for _ in range(int(input())):
	s = collections.deque(list(input()))
	t = [s.popleft()]
	while s:
		if s[0] == 'B' and t and (t[-1] == 'A'):
			t.pop()
			s.popleft()
		else:
			t.append(s.popleft())
	if t:
		ans = len(t)
		j = 0
		while j < len(t) - 1:
			if t[j] == t[j + 1] == 'B':
				ans -= 2
				j += 2
			else:
				j += 1
		print(ans)
	else:
		print(len(s))


def solve(s):
	stack = []
	for ch in s:
		stack.append(ch)
		while len(stack) > 1 and ''.join(stack[-2:]) in ('AB', 'BB'):
			del stack[-2:]
	return len(stack)
for _ in range(int(input())):
	s = input()
	print(solve(s))


for _ in range(int(input())):
	c = 0
	for i in input():
		c = c - 1 if i == 'B' and c != 0 else c + 1
	print(c)


t = int(input())
for j in range(t):
	s = input()
	l = []
	for i in range(len(s)):
		if s[i] == 'A' or len(l) == 0:
			l.append(s[i])
		else:
			l.pop()
	print(len(l))


for _ in range(int(input())):
	s = list(input())
	ct = 0
	for i in s:
		if i == 'B' and ct != 0:
			ct -= 1
		else:
			ct += 1
	print(ct)


import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
from math import gcd, ceil

def prod(a, mod=10 ** 9 + 7):
	ans = 1
	for each in a:
		ans = ans * each % mod
	return ans

def lcm(a, b):
	return a * b // gcd(a, b)

def binary(x, length=16):
	y = bin(x)[2:]
	return y if len(y) >= length else '0' * (length - len(y)) + y
for _ in range(int(input()) if True else 1):
	s = input()
	n = len(s)
	i = 0
	j = 0
	k = 0
	ans = 0
	while i < n:
		if s[i] == 'A':
			j += 1
		elif j:
			ans += 2
			j -= 1
		else:
			k += 1
			if k % 2 == 0:
				ans += k
				k = 0
		i += 1
	print(n - ans)


from sys import stdin, stdout
import math
import heapq
import collections
input = stdin.readline

def inputnum():
	return int(input())

def inputnums():
	return map(int, input().split())

def inputlist():
	return list(map(int, input().split()))

def inputstring():
	return [x for x in input()]

def inputstrings():
	return [x for x in input().split()]

def inputstringnum():
	return [ord(x) - ord('a') for x in input()]

def inputmatrixchar(rows):
	arr2d = [[j for j in input().strip()] for i in range(rows)]
	return arr2d

def inputmatrixint(rows):
	arr2d = []
	for _ in range(rows):
		arr2d.append([int(i) for i in input().split()])
	return arr2d
t = int(input())
for q in range(t):
	s = inputstring()
	A = 0
	B = 0
	for i in range(len(s) - 1):
		if s[i] == 'A':
			A += 1
		else:
			B += 1
		if A > 0 and s[i] == 'B':
			A -= 1
			B -= 1
	print(A + B % 2)


t = int(input())
for i in range(t):
	line = input().strip()
	n = len(line)
	res = n
	fore = 0
	for i in range(n):
		if fore == 0:
			fore += 1
		elif line[i] == 'A':
			fore += 1
		else:
			fore -= 1
			res -= 2
	print(res)


T = int(input())
for Tid in range(T):
	s = input()
	n = len(s)
	(s0, s1) = (0, 0)
	for i in range(n):
		if s[i:i + 1] == 'A':
			s1 = s1 + 1
		elif s1:
			s1 -= 1
		else:
			s0 += 1
	print(s0 % 2 + s1)


import math
for _ in range(int(input())):
	s = input()
	cnt = 0
	for i in s:
		if i == 'B' and cnt != 0:
			cnt -= 1
		else:
			cnt += 1
	print(cnt)


def blow_up_string(s):
	a_counter = 0
	b_counter = 0
	for i in s[::-1]:
		if i == 'B':
			b_counter += 1
		elif i == 'A':
			if b_counter > 0:
				b_counter -= 1
			else:
				a_counter += 1
	return a_counter + b_counter % 2
for i in range(int(input())):
	print(blow_up_string(input()))


for _ in range(int(input())):
	s = input()
	num = []
	for i in s:
		if len(num) > 0:
			if num[-1] == i and i == 'B':
				num.pop()
			elif i == 'B' and num[-1] == 'A':
				num.pop()
			else:
				num.append(i)
		else:
			num.append(i)
	print(len(num))


t = int(input())
for case in range(t):
	s = input()
	n = len(s)
	ans = 0
	b_count = 0
	for char in s[::-1]:
		if char == 'A':
			if b_count > 0:
				b_count -= 1
			else:
				ans += 1
		else:
			b_count += 1
	print(ans + b_count % 2)


import sys
import math

def get_array():
	return list(map(int, sys.stdin.readline().strip().split()))

def get_ints():
	return map(int, sys.stdin.readline().strip().split())

def input():
	return sys.stdin.readline().strip()
for _ in range(int(input())):
	s = input()
	n = len(s)
	ans = []
	for i in range(n):
		if len(ans) == 0:
			ans.append(s[i])
		elif s[i] == 'A':
			ans.append(s[i])
		elif s[i] == 'B':
			ans.pop(-1)
	print(len(ans))


for i in range(int(input())):
	s = input()
	stock = 0
	for item in s:
		if stock == 0 or item == 'A':
			stock += 1
		else:
			stock -= 1
	print(stock)


t = int(input())
for _ in range(t):
	s = input()
	stack = []
	for i in s:
		if len(stack) == 0:
			stack.append(i)
		elif i == 'A':
			stack.append(i)
		elif i == 'B':
			stack.pop(-1)
	print(len(stack))


from sys import stdin, stdout
for _ in range(int(stdin.readline())):
	s = input()
	q = []
	p = 0
	for ch in s:
		if p == 0:
			q += [ch]
			p += 1
		elif q[p - 1] + ch in ['AB', 'BB']:
			p -= 1
		else:
			q += [ch]
			p += 1
	print(p)


from math import *
import sys
from sys import stdin
from sys import stdout
for __ in range(int(input())):
	s = input()
	stack = []
	for i in range(len(s)):
		if len(stack) == 0:
			stack.append(s[i])
		elif s[i] == 'B':
			stack.pop()
		else:
			stack.append(s[i])
	print(len(stack))


import sys
ii = lambda : sys.stdin.readline().strip()
idata = lambda : [int(x) for x in ii().split()]

def solve():
	s = ii()
	n = len(s)
	cnt = 0
	for i in range(n):
		if s[i] == 'A':
			cnt += 1
		else:
			cnt = max(0, cnt - 1)
	print(cnt + (n - cnt) % 2)
	return
for t in range(int(ii())):
	solve()


def solution(t: int, arr: [str]) -> [int]:
	result = []
	for n in arr:
		stack = []
		for j in n:
			if j == 'A' or len(stack) <= 0:
				stack.append(j)
			else:
				stack.pop()
		result.append(len(stack))
	return result

def main():
	t = int(input())
	arr = [input() for i in range(t)]
	print('\n'.join([str(i) for i in solution(t, arr)]))
main()


t = int(input())
for _ in range(t):
	not_destroed = 0
	s = str(input())
	b = 0
	E = 0
	s = s[::-1]
	for i in range(len(s)):
		if s[i] == 'A':
			if b == 0:
				E += 1
			else:
				b -= 1
		else:
			b += 1
	print(E + b % 2)


for _ in range(int(input())):
	s = input()
	l = len(s)
	(chk, cnt) = ([0] * l, 0)
	a = []
	for i in range(l):
		if s[i] == 'A':
			a.append(i)
		elif a:
			cnt += 1
			idx = a.pop()
			chk[i] = 1
			chk[idx] = 1
	cont = 0
	for i in range(l):
		if chk[i]:
			continue
		if s[i] == 'B':
			cont += 1
		else:
			cnt += cont // 2
			cont = 0
	cnt += cont // 2
	print(l - 2 * cnt)


a = 0
n = int(input())
for i in range(n):
	Str = input()
	x = list(map(str, Str))
	for j in x:
		if j == 'B' and a != 0:
			a = a - 1
		else:
			a = a + 1
	print(a)
	a = 0


for _ in range(int(input())):
	s = input()
	count = 0
	for elem in s:
		if elem == 'B' and count != 0:
			count -= 1
		else:
			count += 1
	print(count)


from collections import deque
t = int(input())
for i in range(t):
	w = input()
	p = deque()
	for i in range(len(w)):
		if len(p) is 0:
			p.append(w[i])
		elif p[-1] == 'A' and w[i] == 'B':
			p.pop()
		elif p[-1] == 'B' and w[i] == 'B':
			p.pop()
		else:
			p.append(w[i])
	print(len(p))


for _ in ' ' * int(input()):
	a = input()
	(o, o1) = (0, 0)
	for i in a:
		if i == 'A':
			o += 1
		elif o:
			o -= 1
		elif o1:
			o1 -= 1
		else:
			o1 += 1
	print(o + o1)


from __future__ import division, print_function
from fractions import Fraction
import sys
import os
from io import BytesIO, IOBase
from heapq import *
from math import gcd, factorial, floor, ceil
from copy import deepcopy
from collections import deque
from bisect import bisect_left as bl
from bisect import bisect_right as br
from bisect import bisect
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')

def print(*args, **kwargs):
	(sep, file) = (kwargs.pop('sep', ' '), kwargs.pop('file', sys.stdout))
	at_start = True
	for x in args:
		if not at_start:
			file.write(sep)
		file.write(str(x))
		at_start = False
	file.write(kwargs.pop('end', '\n'))
	if kwargs.pop('flush', False):
		file.flush()
if sys.version_info[0] < 3:
	(sys.stdin, sys.stdout) = (FastIO(sys.stdin), FastIO(sys.stdout))
else:
	(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
from types import GeneratorType

def iterative(f, stack=[]):

	def wrapped_func(*args, **kwargs):
		if stack:
			return f(*args, **kwargs)
		to = f(*args, **kwargs)
		while True:
			if type(to) is GeneratorType:
				stack.append(to)
				to = next(to)
				continue
			stack.pop()
			if not stack:
				break
			to = stack[-1].send(to)
		return to
	return wrapped_func
mod = 10 ** 9 + 7

def inp():
	return sys.stdin.readline().rstrip('\r\n')

def out(var):
	sys.stdout.write(str(var))

def lis():
	return list(map(int, inp().split()))

def stringlis():
	return list(map(str, inp().split()))

def sep():
	return map(int, inp().split())

def strsep():
	return map(str, inp().split())

def zerolist(n):
	return [0] * n

def nextline():
	out('\n')

def testcase(t):
	for pp in range(t):
		solve(pp)

def printlist(a):
	for p in range(0, len(a)):
		out(str(a[p]) + ' ')

def google(p):
	print('Case #' + str(p) + ': ', end='')

def lcm(a, b):
	return a * b // gcd(a, b)

def power(x, y, p):
	res = 1
	x = x % p
	if x == 0:
		return 0
	while y > 0:
		if y & 1 == 1:
			res = res * x % p
		y = y >> 1
		x = x * x % p
	return res

def ncr(n, r):
	return factorial(n) // (factorial(r) * factorial(max(n - r, 1)))

def isPrime(n):
	if n <= 1:
		return False
	if n <= 3:
		return True
	if n % 2 == 0 or n % 3 == 0:
		return False
	i = 5
	while i * i <= n:
		if n % i == 0 or n % (i + 2) == 0:
			return False
		i = i + 6
	return True

def solve(case):
	s = list(inp())
	n = len(s)
	que = deque([])
	for i in range(n):
		if len(que) == 0:
			que.append(s[i])
		else:
			que.append(s[i])
			f = True
			while f:
				temp = que.pop()
				t2 = que.pop()
				if t2 + temp == 'AB' or t2 + temp == 'BB':
					pass
				else:
					f = False
					que.append(temp)
					que.append(t2)
				if len(que) < 2:
					f = False
	print(len(que))
testcase(int(inp()))


for _ in range(int(input())):
	s = input()
	bank = 0
	count = 0
	for i in range(len(s)):
		if s[len(s) - 1 - i] == 'A':
			if bank > 0:
				bank -= 1
			else:
				count += 1
		if s[len(s) - 1 - i] == 'B':
			bank += 1
	ans = count + bank % 2
	print(ans)


rn = lambda : int(input())
rns = lambda : map(int, input().split())
rl = lambda : list(map(int, input().split()))
rs = lambda : input()
yn = lambda x: print('Yes') if x else print('No')
YN = lambda x: print('YES') if x else print('NO')
pl = lambda l: print(' '.join(list(map(str, l))))
for _ in range(rn()):
	s = rs()
	n = len(s)
	ans = 0
	b = 0
	for i in s[::-1]:
		if i == 'B':
			b += 1
		elif b == 0:
			ans += 1
		else:
			b -= 1
	if b > 0:
		ans += -b % 2
	print(ans)


class Stack:

	def __init__(self):
		self.items = list()

	def is_empty(self):
		return self.items == []

	def peek(self):
		if self.is_empty():
			print('Cannot peek empty stack')
			return
		else:
			return self.items[-1]

	def pop(self):
		if self.is_empty():
			print('Cannot pop an empty stack')
			return
		else:
			return self.items.pop()

	def size(self):
		return len(self.items)

	def push(self, data):
		self.items.append(data)
for _ in range(int(input())):
	text = str(input())
	my_stack = Stack()
	for x in text:
		if x == 'A':
			my_stack.push('A')
		if x == 'B':
			if my_stack.size() > 0:
				my_stack.pop()
			else:
				my_stack.push('B')
	print(my_stack.size())


t = int(input())
while t:
	a = str(input())
	lf = 0
	for i in a:
		if i == 'B' and lf != 0:
			lf -= 1
		else:
			lf += 1
	print(lf)
	t = t - 1


try:
	for i in range(int(input())):
		s = input()
		a = 0
		for i in s:
			if i == 'B' and a != 0:
				a -= 1
			else:
				a += 1
		print(a)
except:
	pass


t = int(input())
for _ in range(t):
	s = input()
	st = []
	for i in s:
		if i == 'A':
			st.append('A')
		elif len(st):
			st.pop(-1)
		else:
			st.append('B')
	print(len(st))


T = int(input())
for _ in range(T):
	s = input()
	N = len(s)
	ans = []
	for c in s:
		if c == 'B':
			if len(ans):
				ans.pop()
			else:
				ans.append(c)
		else:
			ans.append(c)
	print(len(ans))


import sys
import os
from math import sqrt, log, log2, log10, gcd, floor, pow, sin, cos, tan, pi, inf, factorial
from copy import copy, deepcopy
from sys import exit, stdin, stdout
from collections import Counter, defaultdict, deque
from itertools import permutations
import heapq
from bisect import bisect_left as bl
from bisect import bisect_right as br
from bisect import bisect
mod = 1000000007
iinp = lambda : int(sys.stdin.readline())
inp = lambda : sys.stdin.readline().strip()
strl = lambda : list(inp().strip().split(' '))
intl = lambda : list(map(int, inp().split(' ')))
mint = lambda : map(int, inp().split())
flol = lambda : list(map(float, inp().split(' ')))
flush = lambda : stdout.flush()

def permute(nums):

	def fun(arr, nums, cur, v):
		if len(cur) == len(nums):
			arr.append(cur.copy())
		i = 0
		while i < len(nums):
			if v[i]:
				i += 1
				continue
			else:
				cur.append(nums[i])
				v[i] = 1
				fun(arr, nums, cur, v)
				cur.pop()
				v[i] = 0
				i += 1
		return arr
	res = []
	nums.sort()
	v = [0] * len(nums)
	return fun(res, nums, [], v)

def subsets(res, index, arr, cur):
	res.append(cur.copy())
	for i in range(index, len(arr)):
		cur.append(arr[i])
		subsets(res, i + 1, arr, cur)
		cur.pop()
	return res

def sieve(N):
	root = int(sqrt(N))
	primes = [1] * (N + 1)
	(primes[0], primes[1]) = (0, 0)
	for i in range(2, root + 1):
		if primes[i]:
			for j in range(i * i, N + 1, i):
				primes[j] = 0
	return primes

def bs(arr, l, r, x):
	if x < arr[0] or x > arr[len(arr) - 1]:
		return -1
	while l <= r:
		mid = l + (r - l) // 2
		if arr[mid] == x:
			return mid
		elif arr[mid] < x:
			l = mid + 1
		else:
			r = mid - 1
	return -1

def isPrime(n):
	if n <= 1:
		return False
	if n <= 3:
		return True
	if n % 2 == 0 or n % 3 == 0:
		return False
	p = int(sqrt(n))
	for i in range(5, p + 1, 6):
		if n % i == 0 or n % (i + 2) == 0:
			return False
	return True

def solve():
	s = inp()
	arr = []
	for i in range(len(s)):
		if not arr:
			arr.append(s[i])
			continue
		if arr[-1] == 'A' and s[i] == 'B':
			arr.pop()
		elif arr[-1] == 'B' and s[i] == 'B':
			arr.pop()
		else:
			arr.append(s[i])
	return len(arr)
for _ in range(iinp()):
	print(solve())


t = int(input())
for _ in range(t):
	s = input()
	a = []
	b = []
	n = len(s)
	ans = 0
	for i in range(n):
		if s[i] == 'A':
			a.append(i)
		else:
			b.append(i)
	p = len(a)
	q = len(b)
	i = 0
	j = 0
	c = 0
	while i < p and j < q:
		if a[i] < b[j]:
			i += 1
			j += 1
			c += 1
		else:
			j += 1
	ans += p - c
	x = q - c
	ans += x % 2
	print(ans)


for _ in range(int(input())):
	s = input()
	stack = []
	for char in s:
		if stack and char == 'B' and (stack[-1] == 'A' or stack[-1] == 'B'):
			stack.pop()
		else:
			stack.append(char)
	print(len(stack))


for t in range(int(input())):
	s = input().strip()
	ans = []
	for i in s:
		if i == 'B':
			if ans:
				if ans[-1] == 'B' or ans[-1] == 'A':
					ans.pop()
				else:
					ans.append(i)
			else:
				ans.append(i)
		else:
			ans.append(i)
	print(len(ans))


ncases = int(input())
for tcase in range(ncases):
	cdebt = 0
	pairs = 0
	s = input()
	for char in s:
		if char == 'A':
			cdebt += 1
		elif cdebt == 0:
			cdebt += 1
		else:
			cdebt -= 1
			pairs += 1
	print(len(s) - pairs * 2)


for _ in range(int(input())):
	n = input()
	stack = []
	count = 0
	for i in n:
		if i == 'B':
			if stack and stack[-1] == 'A':
				stack.pop()
				count -= 1
			elif stack and stack[-1] == 'B':
				stack.pop()
				count -= 1
			else:
				stack.append(i)
				count += 1
		else:
			stack.append(i)
			count += 1
	print(count)


for t in range(int(input())):
	s = input()
	stack = []
	for c in s:
		if c == 'A':
			stack.append('A')
		elif stack:
			stack.pop()
		else:
			stack.append('B')
	print(len(stack))


def inp():
	return int(input())

def inlt():
	return list(map(int, input().split()))

def insr():
	s = input()
	return list(s[:len(s)])

def invr():
	return map(int, input().split())
n = inp()
for _ in range(n):
	s = insr()
	a = 0
	b = 0
	ans = 0
	l = []
	for x in s:
		if len(l) >= 2:
			if l[-1] == 'B' and l[-2] == 'A':
				l.pop(-1)
				l.pop(-1)
			elif l[-1] == 'B' and l[-2] == 'B':
				l.pop(-1)
				l.pop(-1)
		l.append(x)
	if len(l) > 1:
		if l[-1] == 'B' and l[-2] == 'A':
			l.pop(-1)
			l.pop(-1)
		elif l[-1] == 'B' and l[-2] == 'B':
			l.pop(-1)
			l.pop(-1)
	print(len(l))


import sys

def input():
	return sys.stdin.readline().strip()

def list2d(a, b, c):
	return [[c for j in range(b)] for i in range(a)]

def list3d(a, b, c, d):
	return [[[d for k in range(c)] for j in range(b)] for i in range(a)]

def list4d(a, b, c, d, e):
	return [[[[e for l in range(d)] for k in range(c)] for j in range(b)] for i in range(a)]

def ceil(x, y=1):
	return int(-(-x // y))

def INT():
	return int(input())

def MAP():
	return map(int, input().split())

def LIST(N=None):
	return list(MAP()) if N is None else [INT() for i in range(N)]

def Yes():
	print('Yes')

def No():
	print('No')

def YES():
	print('YES')

def NO():
	print('NO')
INF = 10 ** 19
MOD = 10 ** 9 + 7
EPS = 10 ** (-10)
for _ in range(INT()):
	S = input()
	N = len(S)
	cnta = cntb = cntab = 0
	for i in range(N):
		if S[i] == 'A':
			cnta += 1
		elif S[i] == 'B' and cnta:
			cntab += 1
			cnta -= 1
		else:
			cntb += 1
	ans = N - cntab * 2 - cntb // 2 * 2
	print(ans)


from sys import stdin, stdout
from collections import Counter
from math import ceil, floor
from bisect import bisect_left
from bisect import bisect_right
import math

def ai():
	return list(map(int, stdin.readline().split()))

def ei():
	return map(int, stdin.readline().split())

def ip():
	return int(stdin.readline().strip())

def op(*args):
	return stdout.write(str(ans) + '\n')

def solve():
	s = input()
	(A_count, B_count) = (0, 0)
	ans = 0
	for i in range(len(s)):
		if s[i] == 'A':
			A_count += 1
		elif s[i] == 'B' and A_count > 0:
			ans += 2
			A_count -= 1
		elif s[i] == 'B':
			B_count += 1
	if B_count % 2:
		B_count -= 1
	print(len(s) - (B_count + ans))
n = ip()
for _ in range(n):
	solve()


import math
from sys import stdin
from sys import setrecursionlimit
setrecursionlimit(100000)

def put():
	return map(int, stdin.readline().split())
for _ in range(int(input())):
	s = input()
	count = 0
	ans = 0
	countb = 0
	for i in s:
		if i == 'A' and count < 0:
			countb -= count
			count = 1
		elif i == 'A':
			count += 1
		else:
			count -= 1
	if count < 0:
		countb -= count
		count = 0
	ans = count
	if countb % 2 == 1:
		ans += 1
	print(ans)


import math
for _ in range(int(input())):
	s = input()
	n = len(s)
	b = 0
	ans = 0
	p = 0
	for i in range(n - 1, -1, -1):
		if s[i] == 'B':
			b += 1
		elif b > 0:
			b -= 1
			ans += 2
	p = b % 2
	ans += b // 2 * 2
	print(n - ans)


import sys, math, cmath, time, collections
start_time = time.time()

def solve():
	s = insr()
	q = [s[0]]
	for i in range(1, len(s)):
		if s[i] == 'B' and q and (q[-1] == 'A'):
			q.pop()
		else:
			q.append(s[i])
	s = ''.join(q)
	if len(s) == 0:
		print(0)
		return
	q = [s[0]]
	for i in range(1, len(s)):
		if s[i] == 'B' and q and (q[-1] == 'B'):
			q.pop()
		else:
			q.append(s[i])
	print(len(q))

def main():
	global tt
	if not ONLINE_JUDGE:
		sys.stdin = open('input.txt', 'r')
		sys.stdout = open('output.txt', 'w')
	t = 1
	t = inp()
	for tt in range(1, t + 1):
		solve()
	if not ONLINE_JUDGE:
		print('Time Elapsed :', time.time() - start_time, 'seconds')
		sys.stdout.close()

def inp():
	return int(input())

def inlt():
	return list(map(int, input().split()))

def insr():
	return input().strip()

def invr():
	return map(int, input().split())

def counter(a):
	q = [0] * max(a)
	for i in range(len(a)):
		q[a[i] - 1] = q[a[i] - 1] + 1
	return q

def counter_elements(a):
	q = dict()
	for i in range(len(a)):
		if a[i] not in q:
			q[a[i]] = 0
		q[a[i]] = q[a[i]] + 1
	return q

def string_counter(a):
	q = [0] * 26
	for i in range(len(a)):
		q[ord(a[i]) - 97] = q[ord(a[i]) - 97] + 1
	return q

def factorial(n, m=1000000007):
	q = 1
	for i in range(n):
		q = q * (i + 1) % m
	return q

def factors(n):
	q = []
	for i in range(1, int(n ** 0.5) + 1):
		if n % i == 0:
			q.append(i)
			q.append(n // i)
	return list(sorted(list(set(q))))

def prime_factors(n):
	q = []
	while n % 2 == 0:
		q.append(2)
		n = n // 2
	for i in range(3, int(n ** 0.5) + 1, 2):
		while n % i == 0:
			q.append(i)
			n = n // i
	if n > 2:
		q.append(n)
	return list(sorted(q))

def transpose(a):
	(n, m) = (len(a), len(a[0]))
	b = [[0] * n for i in range(m)]
	for i in range(m):
		for j in range(n):
			b[i][j] = a[j][i]
	return b

def power_two(x):
	return x and (not x & x - 1)

def ceil(a, b):
	return -(-a // b)

def seive(n):
	a = [1]
	prime = [True for i in range(n + 1)]
	p = 2
	while p * p <= n:
		if prime[p] == True:
			for i in range(p ** 2, n + 1, p):
				prime[i] = False
		p = p + 1
	for p in range(2, n + 1):
		if prime[p]:
			a.append(p)
	return a
ONLINE_JUDGE = __debug__
if ONLINE_JUDGE:
	input = sys.stdin.readline
main()


for _ in range(int(input())):
	x = input()
	c = 0
	for i in range(len(x)):
		if x[i] == 'B' and i - c != 0:
			c += 2
	print(len(x) - c)


import sys
input = sys.stdin.readline
I = lambda : list(map(int, input().split()))
(t,) = I()
for _ in range(t):
	s = input().strip()
	st = []
	n = len(s)
	for i in range(n):
		if st and st[-1] + s[i] in ['AB', 'BB']:
			st.pop()
		else:
			st.append(s[i])
	print(len(st))


for t in range(int(input())):
	s = input()
	stack = []
	for i in s:
		if i == 'A':
			stack.append(i)
		elif stack:
			stack.pop()
		else:
			stack.append(i)
	print(len(stack))


import math
t = int(input())
for k1 in range(t):
	s = input()
	ans = 0
	for i in s:
		if i == 'B' and ans != 0:
			ans -= 1
		else:
			ans += 1
	print(ans)


import sys
input = lambda : sys.stdin.readline().strip()
for EOFError in range(int(input())):
	FloatingPointError = input()
	KeyError = 0
	for LookupError in FloatingPointError:
		if LookupError == 'B' and KeyError != 0:
			KeyError -= 1
		else:
			KeyError += 1
	print(KeyError)


T = int(input())
for __ in range(T):
	s = input()
	(b, a) = (0, 0)
	for c in s:
		if c == 'A':
			a += 1
		elif a > 0:
			a -= 1
		elif b > 0:
			b -= 1
		else:
			b += 1
	print(a + b)


for _ in range(int(input())):
	s = input()
	stack = [s[0]]
	for i in range(1, len(s)):
		if len(stack) != 0:
			if s[i] == 'B' and stack[-1] == 'A':
				stack.pop()
			elif s[i] == 'B' and stack[-1] == 'B':
				stack.pop()
			else:
				stack.append(s[i])
		else:
			stack.append(s[i])
	if len(stack) > 0:
		if stack[0] == 'B' and len(set(stack)) == 1:
			if len(stack) % 2 == 0:
				ans = 0
			else:
				ans = 1
		else:
			ans = len(stack)
	else:
		ans = 0
	print(ans)


for test in range(int(input())):
	s = list(input())
	arr = []
	for x in s:
		arr.append(x)
		if len(arr) > 1:
			if arr[-2] == 'A':
				if arr[-1] == 'B':
					arr.pop()
					arr.pop()
			elif arr[-2] == 'B':
				if arr[-1] == 'B':
					arr.pop()
					arr.pop()
	print(len(arr))


t = int(input())
for _ in range(t):
	string = input()
	arr = []
	nb = 0
	for ch in string:
		if ch == 'A':
			arr.append(ch)
		elif len(arr) == 0:
			nb += 1
		else:
			arr.pop(-1)
	print(nb % 2 + len(arr))


t = int(input())
for _ in range(t):
	s = input()
	ans = 0
	l = len(s)
	ac = 0
	bc = 0
	if s[0] == 'A':
		ac = 1
	for i in range(1, l):
		if s[i] == 'A':
			ac += 1
		else:
			bc += 1
			if ac > 0:
				ac -= 1
				bc -= 1
	if s[0] == 'B':
		bc += 1
	if ac > 0:
		print(ac + bc % 2)
	else:
		print(bc % 2)


for i in range(int(input())):
	s = input()
	ca = 0
	for each in s:
		if each == 'A':
			ca += 1
		elif ca and each == 'B':
			ca -= 1
		else:
			ca += 1
	print(ca)


from collections import Counter, defaultdict
I = lambda : int(input())
M = lambda : map(int, input().split())
LI = lambda : list(map(int, input().split()))
for _ in range(I()):
	s = input()
	ans = 0
	for i in s:
		if i == 'B' and ans != 0:
			ans -= 1
		else:
			ans += 1
	print(ans)


from collections import deque, defaultdict

def solve():
	s = input()
	a = b = na = 0
	for i in s:
		if i == 'A':
			a += 1
			na += 1
		elif a > 0:
			a -= 1
		else:
			b += 1
	if b % 2 == 0:
		b = 0
	else:
		b = 1
	print(a + b)

def main():
	t = 1
	t = int(input())
	for _ in range(t):
		solve()
main()


from sys import stdin, stdout
from math import gcd
input = stdin.readline
for _ in range(int(input())):
	s = input()[:-1]
	a = b = 0
	for i in s:
		if i == 'A':
			a += 1
		elif a:
			a -= 1
		else:
			b += 1
	print(a + (b & 1))


def main():
	for _ in range(int(input())):
		a = list(input())
		(ca, cb, ans) = (0, 0, 0)
		for i in a[::-1]:
			if i == 'A':
				ca += 1
			else:
				cb += 1
			if ca > cb:
				ans += (ca + cb) // 2 * 2
				ca = 0
				cb = 0
		ans += (ca + cb) // 2 * 2
		print(len(a) - ans)
main()


for u in range(int(input())):
	s = input()
	n = len(s)
	l = []
	for i in range(n):
		if l == []:
			l.append(s[i])
		elif s[i] == 'B':
			l.pop()
		else:
			l.append(s[i])
	print(len(l))


t = int(input())
for i in range(t):
	a = str(input())
	suma = 0
	sumb = 0
	for i in range(len(a)):
		if a[i] == 'A':
			suma = suma + 1
		elif suma != 0:
			suma = suma - 1
		else:
			sumb = sumb + 1
	print(suma + sumb % 2)


def solve():
	ab_string = input()
	a_count = 0
	b_count = 0
	for elem in ab_string[::-1]:
		if elem == 'B':
			b_count += 1
		elif b_count > 0:
			b_count -= 1
		else:
			a_count += 1
	b_count = b_count % 2
	print(a_count + b_count)
for _ in range(int(input())):
	solve()


t = int(input())
i = 0
while i < t:
	S = str(input())
	A = 0
	C = 0
	j = 0
	while j < len(S):
		if S[j] == 'A':
			A += 1
		elif S[j] == 'B':
			if A != 0:
				A -= 1
			else:
				C += 1
		j += 1
	B = C % 2
	print(A + B)
	i += 1