分析:直接就这么翻肯定是不行的,换一种想法:有括号就是把括号里的字符串倒着输出,如果在括号里又遇到了括号就继续倒着输出,相当于递归.
我们可以用递归直接做,也可以用一层循环搞定,每次从左括号跳到右括号,再从右括号跳到左括号,之后走一步,就能输出处理后的字符串了,而不会死循环了.
#include <cstdio> #include <cstring> #include <iostream> #include <algorithm> using namespace std; char s[500010]; int tot, pipei[500010], nextt[500010], x, dir; int main() { scanf("%s", s + 1); int sizee = strlen(s + 1); for (int i = 1; i <= sizee; i++) { if (s[i] == '(') pipei[++tot] = i; else if (s[i] == ')') { nextt[i] = pipei[tot]; nextt[pipei[tot--]] = i; } } dir = 1, x = 1; while (x >= 1 && x <= sizee) { if (nextt[x]) { x = nextt[x]; dir = -dir; } else printf("%c", s[x]); x += dir; } return 0; }