标签:
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) { Stack<Character>stack = new Stack<Character>(); String brackets = "({[]})"; char[] list = s.toCharArray(); int size = list.length; for(int i=0;i<size;i++){ if(brackets.indexOf(list[i])<=2){ stack.push(list[i]); } else{ if(stack.empty()){ return false; } char top_char = stack.peek(); int index = 5-brackets.indexOf(top_char); if(list[i] == brackets.charAt(index)){ stack.pop(); } else{ return false; } } } if(stack.empty()){ return true; } else{ return false; } } }
标签:
原文地址:http://www.cnblogs.com/mrpod2g/p/4265433.html