20743: 整人的提词本
http://cs101.openjudge.cn/practice/20743/
剧组为了整演员,提供给他们的提词本是经过加工的
提词本内容由英文字母跟括号组成,而且括号必定合法,左括号一定有对应的右括号
演员必须从最里层开始翻转括号内的字母
例如(dcba) 要翻转成abcd
最终演员所念的台词不能含有括号
请输出演员应该念出来的台词
输入
一个字串s
输出
一个字串s2
样例输入
(eg(en(duj))po)样例输出
openjudge提示
先反转duj 再反转enjud 最后反转全部台词
use a stack to keep track of the characters inside each pair of parentheses. When you encounter a closing parenthesis, you pop characters from the stack and reverse them until you reach an opening parenthesis, then push the reversed characters back onto the stack. Continue this process until you've processed the entire string. Finally, join the characters in the stack to form the final string.
用stack做,碰到后括号说明到了一层结尾了,进栈,用temp做反向处理,然后去掉头括号,合并 stack,继续,最后弹出
python
def reverse_parentheses(s):
stack = []
for char in s:
if char == ')':
temp = []
while stack and stack[-1] != '(':
temp.append(stack.pop())
# remove the opening parenthesis
if stack:
stack.pop()
# add the reversed characters back to the stack
stack.extend(temp)
else:
stack.append(char)
return ''.join(stack)
# 读取输入并处理
s = input().strip()
print(reverse_parentheses(s))