码迷,mamicode.com
首页 > 其他好文 > 详细

20_Valid-Parentheses

时间:2018-06-17 12:30:50      阅读:170      评论:0      收藏:0      [点我收藏+]

标签:time   put   source   turn   public   top   def   ring   als   

20_Valid-Parentheses

[TOC]

Description

Given a string 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.

Note that an empty string is also considered valid.

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

Solution

Java solution 1

class Solution {
    public boolean isValid(String s) {
        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.empty()) {
                    return false;
                }

                char topChar = stack.pop();
                if (c == ')' && topChar != '(') {
                    return false;
                }
                if (c == ']' && topChar != '[') {
                    return false;
                }
                if (c == '}' && topChar != '{') {
                    return false;
                }
            }
        }

        return stack.isEmpty();
    }
}

Runtime:?15 ms

Java solution 2 (Better!)

class Solution {
    public boolean isValid(String s) {
        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() || c != stack.pop()) {
                return false;
            }
        }
        return stack.isEmpty();
    }
}

Runtime:?12 ms

Python solution

class Solution:
    def isValid(self, s):
        """
        :type s: str
        :rtype: bool
        """
        stack = list()
        dict = {'(': ')', '[': ']', '{': '}'}
        for c in s:
            if c in dict.keys():
                stack.append(dict[c])
            elif c in dict.values():
                if len(stack) == 0 or c != stack.pop():
                    return False
            else:
                False
        return len(stack) == 0

Runtime:?40 ms

20_Valid-Parentheses

标签:time   put   source   turn   public   top   def   ring   als   

原文地址:https://www.cnblogs.com/xugenpeng/p/9192495.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!