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) { Stack<Character> st=new Stack<Character>(); for(int i=0;i<s.length();i++){ char c=s.charAt(i); if(c==‘(‘||c==‘{‘||c==‘[‘){ st.push(c); } else if(c==‘)‘||c==‘}‘||c==‘]‘){ if(st.size()==0){ return false; } char cp=st.pop(); if(c==‘)‘&&cp==‘(‘){ continue; } else if(c==‘}‘&&cp==‘{‘){ continue; } else if(c==‘]‘&&cp==‘[‘){ continue; } return false; } } return st.size()==0; } }
【Leetcode】Valid Parentheses,布布扣,bubuko.com
原文地址:http://blog.csdn.net/chongshijing/article/details/26091297