Valid Parentheses


import java.util.Stack;
public class JudgeExact { public static boolean isValid(String s) { if (s == null || s.length() == 0) { return false; } char[] cset = s.toCharArray(); Stack<Character> characters = new Stack<Character>(); int i = 0; int len = cset.length; if (len == 1) { return false; } while (i < len) { if (characters.isEmpty()) { characters.add(cset[i]); } else { char left = characters.peek(); char right = cset[i]; if ((left == '{' && right == '}') || (left == '(' && right == ')') || (left == '[' && right == ']')) { characters.pop(); } else { characters.push(cset[i]); } } i++; } if (characters.isEmpty()) { return true; } return false; } public static void main(String[] args) { System.out.println(JudgeExact.isValid("{")); } }

 

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.

posted @ 2015-09-14 21:26  程序猿进化之路  阅读(116)  评论(0)    收藏  举报