leetcode-20. Valid Parentheses

来源:互联网 发布:mac个人文件存放在哪里 编辑:程序博客网 时间:2024/05/17 06:16

leetcode-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.

基本思路就用栈去匹配最近的一个左括号。

public class Solution {    public boolean isValid(String s) {        if(s.length()<1)return true;        Stack<Character> sta = new Stack<Character>();        sta.push(s.charAt(0));        for(int i = 1 ; i < s.length() ; i++){            char c = s.charAt(i);            if(c=='(' ||c=='{' ||c=='[')    sta.push(c);            if(c==')')  if(sta.isEmpty() || '('!=sta.pop())  return false;            if(c=='}')  if(sta.isEmpty() || '{'!=sta.pop())  return false;             if(c==']')  if(sta.isEmpty() || '['!=sta.pop())  return false;         }        return sta.isEmpty();    }}
0 0
原创粉丝点击