P1190反转每对括号间的子串


image-20210526005241504

  • 第一个思路就是用栈,遇到右括号就翻转到左括号为止的字符,直到遍历完整个字符串
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
    class Solution {
public String reverseParentheses(String s) {
Queue<Character> queue = new LinkedList<>();
Stack<Character> stack = new Stack<Character>();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == ')') {
char temp;
while ((temp = stack.pop()) != '(') {
queue.offer(temp);
}
while (!queue.isEmpty()) {
stack.push(queue.poll());
}
} else {
stack.push(c);
}
}
StringBuilder sb = new StringBuilder();
Stack<Character> characters = new Stack<>();
while (!stack.isEmpty()) {
characters.push(stack.pop());
}
while (!characters.isEmpty()) {
sb.append(characters.pop());
}

return sb.toString();
}
}


← Prev P461汉明距离 | Nuxt快速开发前台 Next →