LeetCode 20. Valid Parentheses

原题链接在这里:https://leetcode.com/problems/valid-parentheses/

题目:

Given a string containing just the characters '('')''{''}''[' and ']', determine if the input string is valid.

The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.

题解:

当遇到'(', '[', '{' 时压栈,当遇到')', ']', '}'时观察stk是否为空,若是空,返回false,若不是,pop()出来的第一个元素是否对应,若不对应, 返回false. 读完整个string若stk不空,返回false。若没问题,返回true。

Time Complexity: O(s.length()). Space: O(s.length()).

AC Java:

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

AC C++:

 1 class Solution {
 2 public:
 3     bool isValid(string s) {
 4         stack<char> stk;
 5         for(char c : s){
 6             if(c == '('){
 7                 stk.push(')');
 8             }else if(c == '['){
 9                 stk.push(']');
10             }else if(c == '{'){
11                 stk.push('}');
12             }else{
13                 if(stk.empty() || stk.top() != c){
14                     return false;
15                 }
16 
17                 stk.pop();
18             }
19         }
20 
21         return stk.empty();
22     }
23 };

AC Python:

 1 class Solution:
 2     def isValid(self, s: str) -> bool:
 3         map = {'(': ')', '{': '}', '[': ']'}
 4         stk = []
 5         for c in s:
 6             if c in map:
 7                 stk.append(map[c])
 8             elif not stk or stk.pop() != c:
 9                 return False
10 
11         return not stk

AC JavaScript:

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

类似Longest Valid Parentheses.

posted @ 2015-08-18 12:02  Dylan_Java_NYC  阅读(160)  评论(0编辑  收藏  举报