Using Stack to validate parentheses

 

Question:

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.

Idea: since the validation of the Parentheses require the validation of the symmetry. Hence we can utilize Stack to push and store all the upper bracket in a for loop, and determine all the upcoming lower bracket that whether they match with each other with the peek method.

public boolean isValid(String s) {
Stack<Character> stk=new Stack();
for (int i=0;i<s.length();i++){
switch(s.charAt(i)){
case('{'): stk.push('{'); break;
case('('): stk.push('('); break;
case('['): stk.push('['); break;
case('}'): if (!stk.isEmpty() && stk.peek() == '{') {stk.pop(); break;} else return false;
case(')'): if (!stk.isEmpty() && stk.peek() == '(') {stk.pop(); break;} else return false;
case(']'): if (!stk.isEmpty() && stk.peek() == '[') {stk.pop(); break;} else return false;
default: break;
}
}
return stk.isEmpty();

}

posted @ 2015-05-14 22:59  米丹  阅读(59)  评论(0)    收藏  举报