[leet code] Valid Parentheses

来源:互联网 发布:手工西装淘宝 编辑:程序博客网 时间:2024/06/08 15:25

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.

=============

Analysis:

This is a simple problem, but easy to make mistake when implementing.  Idea of which is to utilize a stack to match symbols.

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

Note that always check if stack is empty before .pop().

0 0
原创粉丝点击