标签:stack etc i++ 思路 bool ini 输入 val article
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.
题目:给定一个仅包括‘(‘
, ‘)‘
, ‘{‘
, ‘}‘
, ‘[‘
和 ‘]‘ 的字符串,检測输入的串是否合法。括号是否配对。
思路:使用一个栈。遇到左括号则压入。遇到右括号则与左括号检測是否匹配,不匹配即false,弹出顶元素,循环。
public boolean isValid(String s){ int len = s.length(); if(len <= 1) return false; if(s.charAt(0) == ‘)‘ || s.charAt(0)==‘]‘ || s.charAt(0)==‘}‘) return false; Stack<Character> stack = new Stack<Character>(); for(int i=0;i<len;i++){ if(s.charAt(i) == ‘(‘ || s.charAt(i)==‘[‘ || s.charAt(i)==‘{‘) stack.push(s.charAt(i)); else{ if(stack.size() == 0) return false; if(s.charAt(i) == ‘)‘) if(stack.peek() != ‘(‘) return false; if(s.charAt(i) == ‘]‘) if(stack.peek() != ‘[‘) return false; if(s.charAt(i) == ‘}‘) if(stack.peek() != ‘{‘) return false; stack.pop(); } } return stack.size() == 0; }
标签:stack etc i++ 思路 bool ini 输入 val article
原文地址:http://www.cnblogs.com/slgkaifa/p/6984670.html