第423题-有效的括号序列
描述
给定一个字符串所表示的括号序列,包含以下字符: '('
、')'
、'{'
、'}'
、'['
和 ']'
, 判定是否是有效的括号序列,有效括号序列满足以下条件:
- 左括号必须用相同类型的右括号闭合
- 左括号必须以正确的顺序闭合
- 每个右括号都有一个对应的相同类型的左括号
样例 1:
输入:
s = "([)]"
输出:
False
样例 2:
输入:
s = "(){}[]"
输出:
True
样例 3:
输入:
s = "({})"
输出:
True
样例 4:
输入:
s = "({[()]})"
输出:
True
代码如下:
public class Solution {
/**
* @param s: A string
* @return: whether the string is a valid parentheses
*/
public boolean isValidParentheses(String s) {
// write your code here
// 使用栈来匹配括号
Stack<Character> strStack = new Stack<>();
int n = s.length();
boolean matchFlag = true;
// 遍历字符串
for (int i = 0; i < n; i++) {
char currentChar = s.charAt(i);
// 左括号入栈
if (currentChar == '('||currentChar=='['||currentChar=='{') {
strStack.push(currentChar);
}
// 右括号检查栈顶
else if (currentChar == ')'||currentChar==']'||currentChar=='}') {
if(strStack.isEmpty())//出现左括号不够的情况
{
return false; // 没有匹配的左括号
}else
{
Character popCharacter= strStack.pop();
if(!match(popCharacter,currentChar))
{
return false;
}
}
// 栈顶必须是左括号
}
}
if(!strStack.isEmpty())//出现只有左括号的情况
{
return false;
}else
{
return true;
}
}
boolean match(Character A,Character B)
{
if(A=='{'&&B=='}')
{
return true;
}else if(A=='['&&B==']')
{
return true;
}else if(A=='('&&B==')')
{
return true;
}else
{
return false;
}
}
}