题目链接:https://leetcode.com/problems/valid-parentheses/
题目: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> temp=new Stack<Character>();
boolean flag=true;
for(int i=0;i<s.length();i++)
{
/**
* 遇到'('、'['、'{'均入栈,遇到')'、']'、'}'则检查栈顶元素是否与之匹配
*/
switch (s.charAt(i))
{
case '(':
temp.push('(');
break;
case '[':
temp.push('[');
break;
case '{':
temp.push('{');
break;
case ')':
if(temp.isEmpty()||temp.pop()!='(')
{
flag=false;
}
break;
case ']':
if(temp.isEmpty()||temp.pop()!='[')
{
flag=false;
}
break;
case '}':
if(temp.isEmpty()||temp.pop()!='{')
{
flag=false;
}
break;
default:
break;
}
if(!flag)
break;
}
if(flag&&temp.isEmpty())
return true;
else
return false;
}
}