Problem:


Score : 300 points

Problem Statement

We have a string X, which has an even number of characters. Half the characters are S, and the other half are T.

Takahashi, who hates the string ST, will perform the following operation 10^{10000} times:

Among the occurrences of ST in X as (contiguous) substrings, remove the leftmost one. If there is no occurrence, do nothing.

Find the eventual length of X.

Constraints

2 ≦ |X| ≦ 200,000

The length of X is even.

Half the characters in X are S, and the other half are T.

Partial Scores

In test cases worth 200 points, |X| ≦ 200.

Input

The input is given from Standard Input in the following format:

X

Output

Print the eventual length of X.

Sample Input 1

TSTTSS

Sample Output 1

4

In the 1-st operation, the 2-nd and 3-rd characters of TSTTSS are removed.
X becomes TTSS, and since it does not contain ST anymore, nothing is done in the remaining 10^{10000}-1 operations.
Thus, the answer is 4.

Sample Input 2

SSTTST

Sample Output 2

0

X will eventually become an empty string: SSTTST ⇒ STST ⇒ ST ⇒ ``.

Sample Input 3

TSSTTTSS

Sample Output 3

4

X will become: TSSTTTSS ⇒ TSTTSS ⇒ TTSS.



Sample input:
TSTTSS


Sample output:
4

Submission status: Accepted

Solution code:
def main():
    from sys import setrecursionlimit, stdin
    from os import environ
    from collections import defaultdict, deque, Counter
    from math import ceil, floor
    from itertools import accumulate, combinations, combinations_with_replacement
    setrecursionlimit(10**6)
    dbg = (lambda *something: print(*something)) if 'TERM_PROGRAM' in environ else lambda *x: 0
    input = lambda: stdin.readline().rstrip()
    LMIIS = lambda: list(map(int,input().split()))
    II = lambda: int(input())
    P = 10**9+7
    INF = 10**9+10

    S = input()
    num_s = 0
    ans = len(S)
    for c in S:
        if c == 'S':
            num_s += 1
        else:
            if num_s > 0:
                num_s -= 1
                ans -= 2
    print(ans)

    
main()

Submission status: Accepted

Solution code:

import sys
sys.setrecursionlimit(10 ** 8)

def Z(): return int(input())
def ZZ(): return [int(_) for _ in input().split()]

def main():
    X = input()
    s = False
    c = cc = 0
    for i in range(len(X)):
        if X[i] == 'S':
            s = True
            cc += 1
        else:
            s = False
            if cc > 0:
                cc -= 1
                c += 1
    print(len(X)-2*c)

    return

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
S = input()

t = 0
stock = 0
for c in S:
    if c == "S":
        stock += 1
    elif stock == 0:
        t += 1
    else:
        stock -= 1
print(t + stock)

Submission status: Accepted

Solution code:
x = input()

ans = 0
stock = 0

for i in range(len(x)):
    if x[i] == 'S':
        stock += 1
    elif stock > 0:
        stock -= 1
    else:
        ans += 1

print(ans+stock)

Submission status: Accepted

Solution code:
from collections import deque
d = deque()
X = input()
for c in X:
    if d:
        last = d.pop()
        if last == "S" and c == "T":
            pass
        else:
            d.append(last)
            d.append(c)
    else:
        d.append(c)
print(len(d))

Submission status: Accepted

Solution code:
from collections import deque
d = deque()
X = input()
for c in X:
    d.append(c)
    while len(d) >= 2:
        new = d.pop()
        last = d.pop()
        if last == "S" and new == "T":
            continue
        else:
            d.append(last)
            d.append(new)
            break
print(len(d))

Submission status: Accepted

Solution code:
# input()
# int(input())
# map(int, input().split())
# list(map(int, input().split()))
import math
import sys
import bisect
import heapq  # 優先度付きキュー(最小値取り出し)
from collections import deque
inf = 10 ** 15
mod = 10 ** 9 + 7
s = input()
n = len(s)
stack = []
for c in s:
    if c == 'S':
        stack.append(c)
    if c == 'T':
        if stack:
            if stack.pop() == 'T':
                stack.append('T')
                stack.append(c)
        else:
            stack.append(c)
print(len(stack))

Submission status: Accepted

Solution code:
from statistics import median
#import collections
#aa = collections.Counter(a) # list to list || .most_common(2)で最大の2個とりだせるお a[0][0]
from fractions import gcd
from itertools import combinations # (string,3) 3回
from collections import deque
from collections import defaultdict
import bisect
#
#    d = m - k[i] - k[j]
#    if kk[bisect.bisect_right(kk,d) - 1] == d:
#
#
#
# pythonで無理なときは、pypyでやると正解するかも！！
#
#

import sys
sys.setrecursionlimit(10000000)
mod = 10**9 + 7

def readInts():
  return list(map(int,input().split()))
def I():
  return int(input())
X = input()
cnt = 0
ans = 0
for i in range(len(X)):
    if X[i] == 'S':
        cnt += 1
    else:
        if cnt > 0:
            cnt -= 1
            ans += 2
print(len(X) - ans)

Submission status: Accepted

Solution code:

def s0():return input()
def s1():return input().split()
def s2(n):return [input() for x in range(n)]
def s3(n):return [input().split() for _ in range(n)]
def s4(n):return [[x for x in s] for s in s2(n)]
def n0():return int(input())
def n1():return [int(x) for x in input().split()]
def n2(n):return [int(input()) for _ in range(n)]
def n3(n):return [[int(x) for x in input().split()] for _ in range(n)]
def t3(n):return [tuple(int(x) for x in input().split()) for _ in range(n)]
def p0(b,yes="Yes",no="No"): print(yes if b else no)
# from sys import setrecursionlimit
# setrecursionlimit(1000000)
# from collections import Counter,deque,defaultdict
# import itertools
# import math
# import networkx as nx
# from bisect import bisect_left,bisect_right
# from heapq import heapify,heappush,heappop
x=s0()

ans=0
c=0
for s in x:
    if s=="T":
        if c==0:
            ans+=1
        else:
            c-=1
    else:
        c+=1
print(ans*2)

Submission status: Accepted

Solution code:
from collections import deque
X=input()
N=len(X)
cnt=0
sptm=0
ans=0
d=deque()
"""
for i in range(N):
    if X[i]=="S":
        sptm=sptm+1
    if X[i]=="T":
        sptm=sptm-1
    if sptm<0:
        ans=ans+1
        sptm=0
    #print(sptm,ans)
print(ans+max(0,sptm))
"""
for i in range(N):
    d.append(X[i])
    if len(d)>1:
        s1=d.pop()
        s2=d.pop()
        if (s2!="S")or(s1!="T"):
            d.append(s2)
            d.append(s1)
    #print(d)
print(len(d))

Submission status: Accepted

Solution code:
X=input()
N=len(X)
cnt=0
sptm=0
ans=0
for i in range(N):
    if X[i]=="S":
        sptm=sptm+1
    if X[i]=="T":
        sptm=sptm-1
    if sptm<0:
        ans=ans+1
        sptm=0
    #print(sptm,ans)
print(ans+max(0,sptm))

Submission status: Accepted

Solution code:
x = input()
ans = c = 0
for i in x:
    if i=='S':
        c += 1
    else:
        if c>0:
            ans += 1
            c -= 1
print(len(x)-ans*2)

Submission status: Accepted

Solution code:
s=input()
stack=0
x=0#消したペア数
for c in s:
    if c=='S':
        stack+=1
    else:
        if stack>0:
            stack-=1
            x+=1
print(len(s)-x*2)

Submission status: Accepted

Solution code:
x = input()
visited = [0]*(len(x))
ans = 0
s = 0
t = 0
for i in range(len(x)):
    if not visited[i]:
        if x[i:i+2] == "ST":
            ans += 2
            visited[i+1] = 1
        elif x[i] == "S":
            s += 1
        elif x[i] == "T" and s:
            ans += 2
            s -= 1
print(len(x)-ans)

Submission status: Accepted

Solution code:
s = input()
n = len(s)
max_cnt = 0
cnt = 0
for i in range(n):
    if s[i] == 'T':
        cnt += 1
    else:
        cnt -= 1
    max_cnt = max(cnt, max_cnt)
print(2*max_cnt)

Submission status: Accepted

Solution code:
X = input()
ans = len(X)
sc = 0
for x in X:
    if x == "S":
        sc += 1
    elif sc > 0:
        sc -= 1
        ans -= 2
print(ans)

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
from collections import deque
def main():
    X = list(input().rstrip())
    past = deque()
    cnt = 0
    last = X[0]
    for i in range(1,len(X)):
        if last + X[i] == 'ST':
            if len(past) > 0:
                last = past.pop()
            else:
                last = ''
            cnt += 2
        else:
            past.append(last)
            last = X[i]
    print(len(X) - cnt)
        
if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
x = input()
s_q = []
arc = []
for i, v in enumerate(x):
    if v == 'S':
        s_q.append(v)
    else:
        if len(s_q) > 0:
            s_q.pop()
        else:
            arc.append(v)
print(len(s_q)+len(arc))

Submission status: Accepted

Solution code:
X=input()
t=0
s=0
ans=0
for i in range(len(X)):
    if X[i]=="T":
        t+=1
    else:
        s+=1
    ans=max(ans,t-s)
print(ans*2)

Submission status: Accepted

Solution code:
import sys

input_methods=['clipboard','file','key']
using_method=1
input_method=input_methods[using_method]

tin=lambda : map(int, input().split())
lin=lambda : list(IN())
mod=1000000007

#+++++

def main():
	#a = int(input())
	#b , c = tin()
	s = list(input())[:-1]

	count_s = 0
	delete_num=0
	for c in s:
		if c == 'S':
			count_s+=1
		else: #if c == 'T':
			if count_s == 0:
				pass
			else:
				count_s-=1
				delete_num+=2
	return len(s)-delete_num
	
	
#+++++
isTest=False

def pa(v):
	if isTest:
		print(v)
		
def input_clipboard():
	import clipboard
	input_text=clipboard.get()
	input_l=input_text.splitlines()
	for l in input_l:
		yield l

if __name__ == "__main__":
	if sys.platform =='ios':
		if input_method==input_methods[0]:
			ic=input_clipboard()
			input = lambda : ic.__next__()
		elif input_method==input_methods[1]:
			sys.stdin=open('inputFile.txt')
		else:
			pass
		isTest=True
	else:
		pass
		input = sys.stdin.readline
			
	ret = main()
	if ret is not None:
		print(ret)

Submission status: Accepted

Solution code:
x = input()
s = 0
ans = len(x)
for c in x:
    if c=='S':
        s += 1
    elif s>0:
        ans -= 2
        s -= 1
print(ans)

Submission status: Accepted

Solution code:
x = input()
n = len(x)

ans = 0
cnt = 0
for i in range(n):
    if x[i] == 'S':
        cnt += 1
        ans += 1
    else:
        if cnt > 0:
            cnt -= 1
            ans -= 1
        else:
            ans += 1

print(ans)

Submission status: Accepted

Solution code:
x=input()
a=0
ans=0
for i in range(len(x)):
  if x[i]=="T":
    a=a+1
    if a>ans:
      ans=a
  else:
    a=a-1
print(ans*2)

Submission status: Accepted

Solution code:
X = input()

S_cnt = 0
T_cnt = 0
for i in range(len(X)):
    if X[i] == 'S':
        S_cnt += 1
    else:
        if S_cnt > 0:
            S_cnt -= 1
        else:
            T_cnt += 1

print(S_cnt+T_cnt)

Submission status: Accepted

Solution code:
x = input()
depth = 0
min_depth = 0
for char in x:
    if char == 'T':
        depth -= 1
        if depth < min_depth:
            min_depth = depth
    else:
        depth += 1
print(-2*min_depth-depth)

Submission status: Accepted

Solution code:
L=0
R=0
X=list(input())
A=len(X)
for i in range(A):
  if X[i]=="S":
    R=R+1
  elif X[i]=="T":
    if R!=0:
      L=L+1
      R=R-1
print(A-2*L)

Submission status: Accepted

Solution code:
x=input()
l=[]
for i in x:
  if len(l)>0 and l[-1]=='S' and i=='T':
    l.pop()
    continue
  l.append(i)
print(len(l))

Submission status: Accepted

Solution code:
x = input()
cs = 0
ct = 0
prev = ""
n = len(x)
cnt = 0
for i in range(n):
    if x[i] =="S":
        cs+=1
    elif x[i] =="T":
        if cs>0:
            ct+=1
    else:
        cs = 0
        ct = 0
    if cs>0 and ct>0:
        cnt+=1
        cs-=1
        ct-=1
print(n-cnt*2)

Submission status: Accepted

Solution code:
x = input()
from collections import deque

q = deque()
ans = ""
for i in x:
    if i == "S":
        q.append(i)
    else:
        if q:
            q.popleft()
        else:
            ans += "T"
while q:
    ans += q.popleft()
print(len(ans))

Submission status: Accepted

Solution code:
x=input()
cnt=0
ans=0
for s in x:
    if s=="T":
        cnt-=1
    else:
        cnt+=1
    if cnt<0:
        ans+=1
        cnt=0
print(ans+cnt)

Submission status: Accepted

Solution code:
import sys
from collections import deque
readline = sys.stdin.buffer.readline
sys.setrecursionlimit(10 ** 8)
INF = float('inf')
MOD = 10 ** 9 + 7

def main():
    X = readline().decode('utf-8').strip()
    L = len(X)
    S = X[0]
    count = 0
    RLE = []
    for i in range(L):
        if X[i] == S:
            count += 1
        else:
            RLE.append((S,count))
            S = X[i]
            count = 1
        if i==L-1:
            RLE.append((S,count))
    d = deque(RLE)
    if d[0][0] == 'T':
        d.popleft()
    if d[-1][0] == 'S':
        d.pop()
    s = 0
    t = 0
    count = 0
    while d:
        s += d.popleft()[1]
        t = d.popleft()[1]
        if s>=t:
            count += t*2
            s -= t
        else:
            count += s*2
            s = 0
    ans = L-count
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
#
# 　　  ⋀_⋀　 
#　　  (･ω･)  
# .／ Ｕ ∽ Ｕ＼
#  │＊　合　＊│
#  │＊　格　＊│ 
#  │＊　祈　＊│ 
#  │＊　願　＊│ 
#  │＊　　　＊│ 
#      ￣
#
import sys
sys.setrecursionlimit(10**6)
input=sys.stdin.readline
from math import floor,sqrt,factorial,hypot,log #log2ないｙｐ
from heapq import heappop, heappush, heappushpop
from collections import Counter,defaultdict,deque
from itertools import accumulate,permutations,combinations,product,combinations_with_replacement
from bisect import bisect_left,bisect_right
from copy import deepcopy
from fractions import gcd
from random import randint
def ceil(a,b): return (a+b-1)//b
inf=float('inf')
mod = 10**9+7
def pprint(*A): 
    for a in A:     print(*a,sep='\n')
def INT_(n): return int(n)-1
def MI(): return map(int,input().split())
def MF(): return map(float, input().split())
def MI_(): return map(INT_,input().split())
def LI(): return list(MI())
def LI_(): return [int(x) - 1 for x in input().split()]
def LF(): return list(MF())
def LIN(n:int): return [I() for _ in range(n)]
def LLIN(n: int): return [LI() for _ in range(n)]
def LLIN_(n: int): return [LI_() for _ in range(n)]
def LLI(): return [list(map(int, l.split() )) for l in input()]
def I(): return int(input())
def F(): return float(input())
def ST(): return input().replace('\n', '')
def main():
    X=ST()
    stack = []
    for s in X:
        stack.append(s)
        if(stack[-2:]==["S","T"]):
            stack.pop();stack.pop()
    print(len(stack))
if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
from bisect import bisect_right

def cal(X):
    output = []
    for i in range(len(X)):
        if len(output) > 0:
            if output[len(output)-1] == "S" and X[i] == "T":
                output.pop()
            else:
                output.append(X[i])
        else:
            output.append(X[i])

    return len(output)

def main():
    X = input()
    print(cal(X))

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10 ** 5 + 10)


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


def resolve():

    # https://scrapbox.io/fukucchi/%E6%8B%AC%E5%BC%A7%E5%88%97%E3%81%AE%E6%95%B4%E5%90%88%E6%80%A7%E5%95%8F%E9%A1%8C
    # https://atcoder.jp/contests/abc064/tasks/abc064_d

    X = str(input())
    N = len(X)
    stack_rem = 0
    need_left = 0
    pop_cnt = 0

    for i in range(N):
        if X[i] == 'S':
            stack_rem += 1
        elif stack_rem > 0:
            stack_rem -= 1
            pop_cnt += 1
    print(N-pop_cnt*2)


resolve()

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10 ** 5 + 10)


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


def resolve():

    X = str(input())
    stack = 0
    pop = 0
    for i in range(len(X)):
        if X[i] == 'S':
            stack += 1
        elif X[i] == 'T' and stack > 0:
            pop += 1
            stack -= 1
    print(len(X)-pop*2)

resolve()

Submission status: Accepted

Solution code:
x = input()
ans = len(x)
cs = 0
T = False

for i in x:
  if i == 'S':
    if T:
      T = False
    cs += 1
  else:
    if not T:
      T = True
    if cs > 0:
      cs -= 1
      ans -= 2
print(ans)

Submission status: Accepted

Solution code:
import sys
## io ##
def IS(): return sys.stdin.readline().rstrip()
def II(): return int(IS())
def MII(): return list(map(int, IS().split()))
def MIIZ(): return list(map(lambda x: x-1, MII()))
## dp ##
def DD2(d1,d2,init=0): return [[init]*d2 for _ in range(d1)]
def DD3(d1,d2,d3,init=0): return [DD2(d2,d3,init) for _ in range(d1)]
## math ##
def divc(x,y) -> int: return -(-x//y)
def divf(x,y) -> int: return x//y
def gcd(x,y):
    while y: x,y = y,x%y
    return x
def lcm(x,y): return x*y//gcd(x,y)
def enumerate_divs(n):
    """Return a tuple list of divisor of n"""
    return [(i,n//i) for i in range(1,int(n**0.5)+1) if n%i==0]
def get_primes(n=10**3):
    """Return a list of prime numbers n or less"""
    is_prime = [True]*(n+1)
    is_prime[0] = is_prime[1] = False
    for i in range(2, int(n**0.5)+1):
        if not is_prime[i]: continue
        for j in range(i*2, n+1, i): is_prime[j] = False
    return [i for i in range(n+1) if is_prime[i]]
def prime_factor(n):
    """Return a list of prime factorization numbers of n"""
    res = []
    for i in range(2,int(n**0.5)+1):
        while n%i==0: res.append(i); n //= i
    if n != 1: res.append(n)
    return res
## const ##
MOD=10**9+7
## libs ##
import itertools as it
import functools as ft
from collections import deque, Counter
from heapq import heapify, heappop, heappush
from bisect import bisect_left
#======================================================#
def main():
    x = IS()
    stack = []
    for xi in x:
        if xi == 'S':
            stack.append(xi)
        elif xi == 'T':
            if not stack:
                stack.append(xi)
            elif stack[-1] == 'T':
                stack.append(xi)
            elif stack[-1] == 'S':
                stack.pop()
    print(len(stack))

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys
## io ##
def IS(): return sys.stdin.readline().rstrip()
def II(): return int(IS())
def MII(): return list(map(int, IS().split()))
def MIIZ(): return list(map(lambda x: x-1, MII()))
## dp ##
def DD2(d1,d2,init=0): return [[init]*d2 for _ in range(d1)]
def DD3(d1,d2,d3,init=0): return [DD2(d2,d3,init) for _ in range(d1)]
## math ##
def divc(x,y) -> int: return -(-x//y)
def divf(x,y) -> int: return x//y
def gcd(x,y):
    while y: x,y = y,x%y
    return x
def lcm(x,y): return x*y//gcd(x,y)
def enumerate_divs(n):
    """Return a tuple list of divisor of n"""
    return [(i,n//i) for i in range(1,int(n**0.5)+1) if n%i==0]
def get_primes(n=10**3):
    """Return a list of prime numbers n or less"""
    is_prime = [True]*(n+1)
    is_prime[0] = is_prime[1] = False
    for i in range(2, int(n**0.5)+1):
        if not is_prime[i]: continue
        for j in range(i*2, n+1, i): is_prime[j] = False
    return [i for i in range(n+1) if is_prime[i]]
def prime_factor(n):
    """Return a list of prime factorization numbers of n"""
    res = []
    for i in range(2,int(n**0.5)+1):
        while n%i==0: res.append(i); n //= i
    if n != 1: res.append(n)
    return res
## const ##
MOD=10**9+7
## libs ##
import itertools as it
import functools as ft
from collections import deque, Counter
from heapq import heapify, heappop, heappush
from bisect import bisect_left
#======================================================#
def main():
    x = IS()
    s_num = t_num = 0
    cnt = 0
    for i, xi in enumerate(x):
        if xi == 'S':
            s_num += 1
        elif xi == 'T':
            if s_num != 0: t_num += 1
            if s_num == t_num:
                cnt += s_num + t_num
                s_num = t_num = 0
    if s_num != 0 and t_num != 0:
        cnt += min(s_num, t_num)*2
    print(len(x)-cnt)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
X = input()

s = 0
ans = 0
for Xi in X:
    if Xi == 'S':
        s += 1
        ans += 1
    else:
        if s >= 1:
            s -= 1
            ans -= 1
        else:
            ans += 1
print(ans)

Submission status: Accepted

Solution code:
X = input()
num_t = 0
stack = []
for x in X:
  if x == 'S':
    stack.append(x)
  else:
    if stack:
      stack.pop()
    else:
      num_t += 1

print(num_t + len(stack))

Submission status: Accepted

Solution code:
def main():
    import sys
    input = sys.stdin.readline
    sys.setrecursionlimit(10**7)
    from collections import Counter, deque
    from itertools import combinations, permutations, accumulate, groupby, product
    from bisect import bisect_left,bisect_right
    from heapq import heapify, heappop, heappush
    import math
    #from math import gcd

    #inf = 10**17
    #mod = 10**9 + 7

    s = input().rstrip()
    a = 0
    res = 0
    for i in s:
        if i == 'S':
            a += 1
        else:
            if a <= 0:
                res += 1
            else:
                a -= 1
    print(res+a)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
X = input()
Tnum = len(X) // 2
Snum = len(X) // 2
num = 0
ans = 0
for i in X:
    if i == 'T':
        num -= 1
        Tnum -= 1
    else:
        num += 1
        Snum -= 1

    if num < 0:
        ans += 1
        num = 0
print(ans*2)

Submission status: Accepted

Solution code:
#!/usr/bin/env python3

X = input()
N = len(X)
after_x = ""
next_i = 0
# 連続する箇所で部分文字列を作りたい
s_count, t_count = 0, 0
if X[0] == "T":
    # Tから始まる場合、最初の連続するTは確定で残るので切り捨てる
    for i, x in enumerate(X):
        if x == "T":
            after_x += x
        else:
            break
    next_i = i

if len(after_x) != N:
    # 「全ての文字列がT」ではない
    # 残りの文字列について操作する（最初のTは処理したので、必ずSから始まる）
    for i, char in enumerate(X[next_i:]):
        if i == 0:
            # 最初は確定でSから始まる
            s_count += 1
            continue

        if char == "S":
            # Sの場合
            if X[next_i + i - 1] == "T":
                # T->Sの切り替わりのとき
                if t_count >= s_count:
                    # Sを全て使い切り、余ったTは確定で残る
                    after_x += "T" * (t_count - s_count)
                    t_count = 0
                    s_count = 0
                else:
                    # Tを全部使い切り、余ったSは引き継がれる
                    s_count -= t_count
                    t_count = 0
            s_count += 1
        else:
            # Tの場合
            t_count += 1
    last_char = char

    if last_char == "T":
        # Tで終わる場合
        if t_count >= s_count:
            # Sを全て使い切り、余ったTは確定で残る
            after_x += "T" * (t_count - s_count)
            t_count -= s_count
            s_count = 0
        else:
            # Tを全部使い切り、余ったSは引き継がれる
            s_count -= t_count
            t_count = 0
            after_x += "S" * s_count
    else:
        # Sで終わる場合
        after_x += "S" * s_count
# print(after_x)
ans = len(after_x)
print(ans)

Submission status: Accepted

Solution code:
x = input()
t_num = 0
s_num = 0
total = 0
for i in range(len(x)):
  if x[i] == 'S' and t_num == 0:
    s_num += 1
  elif x[i] == 'T':
    t_num += 1
  elif x[i] == 'S' and t_num > 0:
    total += min(s_num, t_num) * 2
    if s_num >= t_num:
      s_num = 1 + s_num - t_num
      t_num = 0
    else:
      s_num = 1
      t_num = 0
total += min(s_num, t_num) * 2
ans = len(x) - total
print(ans)

Submission status: Accepted

Solution code:
x=input()

l=len(x)
stock=0

for i in list(x):
    if i=='S':
        stock+=1
    else:
        if stock>0:
            stock-=1
            l-=2

print(l)

Submission status: Accepted

Solution code:
import sys
from collections import Counter
from collections import deque
def input(): return sys.stdin.readline().strip()
def mp(): return map(int,input().split())
def lmp(): return list(map(int,input().split()))

x=list(input())
n=len(x)
l=[]
for i in range(n):
    if x[i]=="S":
        l.append("S")
    else:
        if len(l)==0:
            l.append("T")
        elif l[-1]=="S":
            l.pop()
        else:
            l.append("T")
print(len(l))

Submission status: Accepted

Solution code:
import sys
readline = sys.stdin.readline

X = readline().rstrip()

cnt = 0
ans = 0
# Sが出たら1増やし、Tが出たら1減らす
# 0のときにTが出たらansを+1する。ans * 2が答え
for i in range(len(X)):
  if X[i] == "S":
    cnt += 1
  else:
    if cnt == 0:
      ans += 1
    else:
      cnt -= 1
      
print(ans * 2)

Submission status: Accepted

Solution code:
def main():
    X = input()
    result = len(X)
    from collections import deque
    d = deque([])
    append = d.appendleft
    pop = d.popleft
    for x in X:
        if x == "S":
            append(x)
        else:
            if len(d) > 0 and d[0] == "S":
                result -= 2
                pop()
            else:
                append(x)
    print(result)
main()

Submission status: Accepted

Solution code:
x = input()
n = len(x)
s = 0
t = 0
cou = 0

for i in range(n):
    if x[i] == "S":
        s += 1
    elif x[i]== "T":
        if s >= 1:
            s -= 1
            cou += 1
print(n - cou * 2)

Submission status: Accepted

Solution code:
x = input()

continus_s = 0
living_t_cnt = 0
for i in range(len(x)):
    if x[i] == 'S':
        if continus_s > 0:
            continus_s = 0
        continus_s -= 1
    else:
        continus_s += 1
        if continus_s > 0:
            living_t_cnt += 1
print(living_t_cnt*2)

Submission status: Accepted

Solution code:
def main():
    X = input()
    s = 0
    ans = len(X)
    for x in X:
        if x == 'S':
            s += 1
        else:
            if s > 0:
                s -= 1
                ans -= 2
    print(ans)
if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
A=list(input())
from collections import deque
que=deque()
for i in A:
   if i=="T":
      if que==deque():
         que.append("T")
      elif que[-1]=="T":
         que.append("T")
      else:
         que.pop()
   else:
      que.append("S")
print(len(que))

Submission status: Accepted

Solution code:
import sys
from collections import deque

X = list(sys.stdin.readline().strip())

s = []
q = deque(X)
while q:
    char = q.popleft()
    if len(s) == 0:
        s.append(char)
        continue
        
    if char == "T" and s[-1] == "S":
        s.pop()

    else:
        s.append(char)

print(len(s))

Submission status: Accepted

Solution code:
# A - STring

X = input()
count = max_count = 0
ST = {'S':-1, 'T':1}

for i in range(len(X)):
    count += ST[X[i]]
    if count > max_count:
        max_count = count

print(2*max_count)

Submission status: Accepted

Solution code:
X=input()
N=len(X)
stack=[]
ans=0

for i in range(N):
  if X[i]=="S":
    stack.append(X[i])
  else:
    if len(stack)>0:
      stack.pop()
    else:
      ans += 1
ans += len(stack)

print(ans)

Submission status: Accepted

Solution code:
import sys
def input(): return sys.stdin.readline().rstrip()
from collections import deque
def main():
    X=input()
    stack=deque()
    for x in X:
        if x=='S' or (x=='T' and (not stack or stack[-1]=='T')):
            stack.append(x)
        elif stack and stack[-1]=='S':
            stack.pop()
    print(len(stack))
if __name__=='__main__':
    main()

Submission status: Accepted

Solution code:
import sys
def input(): return sys.stdin.readline().rstrip()
from collections import Counter
def main():
    X=input()
    cunt=0
    cunt_s=0
    for x in X:
        if x=='S':
            cunt_s+=1
        elif cunt_s>0:
            cunt_s-=1
        else:
            cunt+=1
    print(cunt+cunt_s)

if __name__=='__main__':
    main()

Submission status: Accepted

Solution code:
x = str(input())
ans = len(x)
ns = 0
for i in x:
    if i == "S":
        ns += 1
    elif ns > 0:
        ans -= 2
        ns -= 1

print(ans)

Submission status: Accepted

Solution code:
# https://atcoder.jp/contests/agc005/tasks/agc005_a

x = input()
ans = len(x)
stack = []
for i in range(len(x)):
    if x[i] == 'S':
        stack.append(x[i])
    elif x[i] == 'T' and stack:
        ans -= 2
        stack.pop()
print(ans)

Submission status: Accepted

Solution code:
X = input()
ans, sc = 0, 0
for x in X:
    if x == 'T':
        sc += 1
    else:
        sc -= 1
    ans = max(ans, sc)
print(ans*2)

Submission status: Accepted

Solution code:
import sys
from collections import deque

input = sys.stdin.readline


def main():
    X = input().rstrip()

    stack = deque()
    for x in X:
        if len(stack) == 0:
            stack.append(x)
        else:
            if x == "S":
                stack.append(x)
            else:
                if stack[-1] == "S":
                    stack.pop()
                else:
                    stack.append(x)
    ans = len(stack)

    print(ans)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
x = input()

stack = []

for c in x:
    if len(stack) == 0:
        stack.append(c)
    elif c == "T" and stack[-1] == "S":
        stack.pop(-1)
    else:
        stack.append(c)

print(len(stack))

Submission status: Accepted

Solution code:
x = list(input())
sta = 0
pop = 0
for i in range(len(x)):
    if x[i] == 'S':
        sta += 1
    elif sta > 0:
        sta -= 1
        pop += 1
print(len(x)-2*pop)

Submission status: Accepted

Solution code:
import numpy as np
import functools
import math
import scipy
import fractions
import itertools
 
def solve():
    x = input()
    a, b = 0, 0
    for i in x:
        if i == "S":
            a += 1
        else:
            if a == 0:
                b += 1
            else:
                a -= 1
    print(a + b)
    return 0

if __name__ == "__main__":
    solve()

Submission status: Accepted

Solution code:
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools
from collections import deque

sys.setrecursionlimit(10**7)
inf = 10**20
mod = 10**9 + 7

DR = [1, -1, 0, 0]
DC = [0, 0, 1, -1]

def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
     
def main():
    x = S()
    s_cnt = 0
    removed = 0
    for c in x:
        if c == 'S':
            s_cnt += 1
        if c == 'T':
            if s_cnt > 0:
                s_cnt -= 1
                removed += 2
    print(len(x) - removed)
main()

Submission status: Accepted

Solution code:
s=list(input())
n=len(s)
from collections import deque
q=deque([])

for i in range(n):
    if s[i]=='S':
        q.append('S')
    else:
        if q:
            if q[-1]=='T':
                q.append('T')
            else:
                q.pop()
        else:
            q.append('T')
print(len(q))

Submission status: Accepted

Solution code:
import sys
from collections import deque
input = sys.stdin.readline


def main():
    X = input().rstrip()

    stack = deque()
    for s in X:
        if s == "S":
            stack.append(s)
        else:
            if len(stack) == 0 or stack[-1] == "T":
                stack.append(s)
            else:
                stack.pop()
    ans = len(stack)
    print(ans)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
from queue import Queue

S = input()
ans = len(S)
Q = Queue()
for s in S:
    if s == 'S':
        Q.put(s)
    else:
        if Q.empty():
            continue
        Q.get()
        ans -= 2
print(ans)