标签:
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 static boolean isValid(String s) { Stack<Character> gt=new Stack<Character>(); int i=0; while(i != s.length()) { char c =s.charAt(i); if (c != ‘)‘ && c != ‘}‘ && c != ‘]‘) { gt.push(c); } else { if (gt.size() == 0) return false; char pre = gt.lastElement(); switch(c) { case ‘)‘: if (pre == ‘(‘) gt.pop(); else return false; break; case ‘}‘: if (pre == ‘{‘) gt.pop(); else return false; break; case ‘]‘: if (pre == ‘[‘) gt.pop(); else return false; break; } } ++i; } if (gt.size() == 0) return true; else return false; } }
标签:
原文地址:http://www.cnblogs.com/gonewithgt/p/4579556.html