[LeetCode] 20. Valid Parentheses

有效的括号。题意是给一个input,请判断他是否是一组有效的括号。例子,

Example 1:

Input: "()"
Output: true
Example 2:

Input: "()[]{}"
Output: true
Example 3:

Input: "(]"
Output: false
Example 4:

Input: "([)]"
Output: false
Example 5:

Input: "{[]}"
Output: true

思路是用stack做。如果看到左半边括号就无条件压入栈;如果看到右半边括号,判断栈是不是为空,为空就报错;栈不为空再判断目前栈顶元素是不是相对应的左半边,若不是也报错。

时间O(n)

空间O(n)

Java实现

 1 class Solution {
 2     public boolean isValid(String s) {
 3         Deque stack = new ArrayDeque<>();
 4         for (char c : s.toCharArray()) {
 5             if (c == '(' || c == '[' || c == '{') {
 6                 stack.push(c);
 7             }
 8             if (c == ')') {
 9                 if (stack.isEmpty() || stack.pop() != '(') return false;
10             }
11             if (c == ']') {
12                 if (stack.isEmpty() || stack.pop() != '[') return false;
13             }
14             if (c == '}') {
15                 if (stack.isEmpty() || stack.pop() != '{') return false;
16             }
17         }
18         return stack.isEmpty();
19     }
20 }

 

JavaScript实现

 1 /**
 2  * @param {string} s
 3  * @return {boolean}
 4  */
 5 var isValid = function(s) {
 6     let stack = [];
 7     for (let i = 0; i < s.length; i++) {
 8         if (s[i] === '(' || s[i] === '[' || s[i] === '{') {
 9             stack.push(s[i]);
10         }
11         if (s[i] === ')') {
12             if (stack.length === 0 || stack.pop() != '(') return false;
13         }
14         if (s[i] === ']') {
15             if (stack.length === 0 || stack.pop() != '[') return false;
16         }
17         if (s[i] === '}') {
18             if (stack.length === 0 || stack.pop() != '{') return false;
19         }
20     }
21     return stack.length === 0 ? true : false;
22 };

你可能感兴趣的:([LeetCode] 20. Valid Parentheses)