给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。
括号必须以正确的顺序关闭,"()" 和 "()[]{}" 是有效的但是 "(]" 和 "([)]" 不是。
详见:https://leetcode.com/problems/valid-parentheses/description/
实现语言:Java
class Solution { public boolean isValid(String s) { Stack<Character> stack=new Stack<>(); Character now; Character prev; int length=s.length(); for(int i=0;i<length;i++){ now=s.charAt(i); if(now=='('||now=='['||now=='{'){ stack.push(now); }else{ if(stack.isEmpty()){ return false; }else{ prev=stack.pop(); } if(now==')'&&prev!='('){ return false; }else if(now==']'&&prev!='['){ return false; }else if(now=='}'&&prev!='{'){ return false; } } } return stack.isEmpty(); } }
参考:https://blog.csdn.net/runningtortoises/article/details/45621933
http://www.cnblogs.com/grandyang/p/4424587.html