20. Valid Parentheses

问题
Given a string s containing just the characters ‘(‘, ‘)’, ‘{‘, ‘}’, ‘[‘ and ‘]’, determine if the input string is valid.

An input string is valid if:

  1. Open brackets must be closed by the same type of brackets.
  2. Open brackets must be closed in the correct order.

用栈储存遍历中的字符。
如果是“(”,“{”或“[”,则入栈。
如果是其他字符,且不与栈顶的字符成对,则返回false。
其他情况需要pop掉栈顶。

  • toCharArray(): 将字符串转换为字符数组,便于遍历。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public boolean isValid(String s) {
Stack<Character> stack = new Stack();

for (char c : s.toCharArray()){
if ( c == '(' || c == '{' || c == '[' ){
stack.push(c);
}
else if ( stack.size() == 0 ||
c == ')' && stack.peek() != '(' ||
c == '}' && stack.peek() != '{' ||
c == ']' && stack.peek() != '[') {
return false;
}
else{
stack.pop();
}
}
return stack.isEmpty();
}
}
Author

Xander

Posted on

2022-04-10

Updated on

2022-04-09

Licensed under

Comments