leetcode20. Valid Parentheses

来源:互联网 发布:2017网络流行语口头禅 编辑:程序博客网 时间:2024/05/29 10:15

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.

由于这道题目限定了字符串中自能有这种6种字符,我就不考虑还有其它字符的情况。

论坛虽然有十几行的代码,但是判断的时候写的很长很复杂。 

我的想法是一个HashMap用来存储左右括号,键用来存储左括号,值用来存储右括号。

再用一个Stack来存储左括号。

我们遍历一遍字符串当遇到左括号(既HashMap中不包含的键),就入Stack。当遇到右括号,分两种情况讨论。

第一种Stack空,那么说明有多余的右括号,就返回False;

第二种是Stack非空,那么取出Stack的Top,以该Top为键,判断该键对应的值是否和当前字符一样,如果不一样返回False,

一样的话,继续遍历字符串。

遍历完,如果Stack非空就返回False,否则True;

public class Solution {    public boolean isValid(String s) {        HashMap<Character, Character> hash = new  HashMap<>();        hash.put('{','}');        hash.put('(',')');        hash.put('[',']');                Stack<Character> stack = new Stack<>();        for(int i =0; i<s.length(); i++){            char c = s.charAt(i);            if(hash.containsKey(c)){                stack.push(c);                continue;            }            if(stack.size()==0){                return false;            }            char pair = (char)(stack.pop());            if(hash.get(pair) != c){                return false;            }        }                if(stack.size()!=0){            return false;        }        return true;    }}


这个算法时间复杂度O(n), 空间复杂度为O(n)。


0 0