Valid Parentheses
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 == null || s.length() == 0) return true; Stack<Character> stack = new Stack<Character>(); for(int i = 0; i < s.length(); i++) { char c = s.charAt(i); if(isRight(c)) { if(stack.isEmpty()) return false; char left = stack.pop(); if(!isMatch(left,c)) return false; } else { stack.push(c); } } return stack.isEmpty(); } public boolean isMatch(char left, char right) { if((left=='('&&right==')')||(left=='['&&right==']')||(left=='{'&&right=='}')) return true; return false; } public boolean isRight(char c) { if(c == ')' || c == ']' || c == '}') return true; return false; } }
posted on 2015-03-13 21:21 zhouzhou0615 阅读(149) 评论(0) 编辑 收藏 举报