zoukankan      html  css  js  c++  java
  • 20. 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.

    链接:http://leetcode.com/problems/valid-parentheses/

    题解: 一道基本的使用stack的题目。 Time Complexity - O(n), Space Complexity - O(n)

    public class Solution {
        public boolean isValid(String s) {
            if(s == null || s.length() == 0)
                return true;
            Stack<Character> stack = new Stack<Character>();
            
            for(int i = 0; i < s.length(); i ++){
                int left = s.charAt(i);
                if(left == '(' || left == '[' || left == '{') 
                    stack.push(s.charAt(i));
                else {
                    if(stack.isEmpty())
                        return false;
                    char right = stack.pop(); 
                    if(left == ']' && right != '[')
                        return false;
                    else if(left == '}' && right != '{')
                        return false;
                    else if (left == ')' && right != '(')
                        return false;
                }
            }
            
            if(!stack.isEmpty())
                return false;
            return true;
        }
    }

    二刷:

    Java:

    这里在想以后要不要把所有的stack都换成linkedlist,因为stack继承自vector,linkedlist继承自list,而vector以后可能会用得很少。

    public class Solution {
        public boolean isValid(String s) {
            if (s == null) {
                return false;
            }
            if (s.length() == 0) {
                return true;
            }
            LinkedList<Character> stack = new LinkedList<>();
            for (int i = 0; i < s.length(); i++) {
                char c = s.charAt(i);
                if (c == ']' || c == '}' || c == ')') {
                    if (stack.size() == 0) {
                        return false;
                    } else {
                        char openChar = stack.removeLast();
                        if ((c == ']' && openChar != '[') || (c == '}' && openChar != '{') || (c == ')' && openChar != '(')) {
                            return false;
                        }
                    }
                } else {
                    stack.add(c);
                }
            }
            return stack.size() == 0;
        }
    }

    Python:

    class Solution(object):
        def isValid(self, s):
            """
            :type s: str
            :rtype: bool
            """
            stack = []
            for i in range(0, len(s)):
                c = s[i]
                if c == ']' or c == '}' or c == ')':
                    if stack == []:
                        return False
                    openChar = stack.pop()
                    if (c == ']' and openChar != '[') or (c == '}' and openChar != '{') or (c == ')' and openChar != '('):
                        return False
                else:
                    stack.append(c)
            return stack == []
            

    三刷:

    写得还是不漂亮, 究竟多个或操作该怎么换行才能优雅好看??

    Java:

    public class Solution {
        public boolean isValid(String s) {
            if (s == null) {
                return false;
            }
            Stack<Character> stack = new Stack<>();
            for (int i = 0; i < s.length(); i++) {
                char c = s.charAt(i);
                if (c == '{' || c == '[' || c == '(') {
                    stack.push(c);
                } else if (stack.isEmpty()) {
                    return false;
                } else {
                    char oChar = stack.pop();
                    if ((c == '}' && oChar != '{') || (c == ']' && oChar != '[') || (c == ')' && oChar != '(')) {
                        return false;
                    }
                }
            }
            return stack.isEmpty();
        }
    }

    Reference:

    https://leetcode.com/discuss/26445/12-lines-of-java

  • 相关阅读:
    MSDN for 2010的那些麻烦事
    CPtrList操作--插入,删除特定元素,删除全部
    如何绕过ORA00701错误和降低bootstrap对象的高水位
    ORA00600:[1112]内部错误&ROW CACHE ENQUEUE LOCK一例
    CRS5008: Invalid attribute value
    ORA00600[kjpsod1]&ORA44203错误一例
    runInstaller ignoreInternalDriverError
    RMAN CURSOR_SHARING=EXACT脚本
    SQL调优:带函数的谓词导致CBO Cardinality计算误差
    11g Real Application Testing:Database Replay使用方法
  • 原文地址:https://www.cnblogs.com/yrbbest/p/4434546.html
Copyright © 2011-2022 走看看