20. Valid Parentheses Easy

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.

Example 1:

1
2
Input: s = "()"
Output: true

Example 2:

1
2
Input: s = "()[]{}"
Output: true

Example 3:

1
2
Input: s = "(]"
Output: false

Example 4:

1
2
Input: s = "([)]"
Output: false

Example 5:

1
2
Input: s = "{[]}"
Output: true

Constraints:

  • 1 <= s.length <= 104
  • s consists of parentheses only '()[]{}'.

思路:

思路一:栈

在栈的那一节中,就提及到了栈的其中一个应用就是括号匹配,大致思路如下:

遇到 ({[ 这三种左括号,直接让它入栈,直到出现 }] ,首先判断栈是否为空或者栈顶的元素是否对应,如果对应,那么让它出栈,继续上述操作即可

代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public boolean isValid(String s) {
if (s == null || s.length() == 0) return true;
Stack<Character> stack = new Stack<>();
for (int i = 0; i < s.length(); i++) {
char temp = s.charAt(i);
if (temp != ')' && temp != ']' && temp != '}') {
stack.push(s.charAt(i));
} else if (temp == ')' && !stack.isEmpty() && stack.peek() == '(' ||
temp == ']' && !stack.isEmpty() && stack.peek() == '[' ||
temp == '}' && !stack.isEmpty() && stack.peek() == '{') {
stack.pop();
} else {
return false;
}
}
return stack.isEmpty();
}

时间复杂度:O(n)

空间复杂度:O(n)

还看到了一种反向写法

代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
public boolean isValid(String s) {
if(s.isEmpty()) { return true; }
Stack<Character> stack = new Stack<>();
for(char c:s.toCharArray()){
if(c == '(') { stack.push(')'); }
else if(c == '[') { stack.push(']'); }
else if(c == '{') { stack.push('}'); }
else if(stack.isEmpty() || stack.pop() != c){
return false;
}
}
return stack.isEmpty();
}

评论