Last time If you have a recommended problem, please leave a comment or twitter. #29 Problem
** Thoughts ** At first, it was implemented normally (reverse), but reverse is expensive, so it needs to be handled well. You can use deques because you can add characters at the beginning or the end. Also, instead of reversing one by one, you can create labels before and after and invert each time you reverse.
from collections import deque
s = deque(input())
q = int(input())
query = [input().split() for _ in range(q)]
reverse = False #Judge before and after
for i in query:
if len(i) == 1:
if reverse:
reverse = False
else:
reverse = True
else:
if reverse:
if i[1] == '1':
s.append(i[2])
else:
s.appendleft(i[2]) #Append at the tip
else:
if i[1] == '1':
s.appendleft(i[2]) #Append at the tip
else:
s.append(i[2])
if reverse: #s must be reversed if reverse is enabled
s = reversed(s)
s = ''.join(s)
print(s)
else:
s = ''.join(s)
print(s)
I think the truth of reverse can be handled better.
I learned that manipulating strings is slow. It seems that it is better to use list or deque rather than str for the problem that the place to operate is decided like this time. see you. good night.
Recommended Posts