LeetCode(20)Valid Parentheses

时间:2022-01-02 08:34:38

题目

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.

分析

典型的括号匹配问题,数据结构一书中的典型实例。其程序实现,借助栈结构是最佳方法。

AC代码

class Solution {
public:
bool isValid(string s) {
int len = strlen(s.c_str());
if (len == 0)
return true;
if (len % 2 != 0)
return false; //括号匹配问题,用数据结构栈辅助实现
stack<char> sta;
for (int i = 0; i < len; i++)
{
if (s[i] != ')' && s[i] != ']' && s[i] != '}')
sta.push(s[i]);
else
{
if (sta.size() <= 0)
return false;
if (s[i] == PairLetter(sta.top()))
sta.pop();
else
return false;
}//else
}//for
if (sta.size() == 0)
return true;
else
return false;
} char PairLetter(const char &c)
{
switch (c)
{
case '(':
return ')'; break;
case '[':
return ']'; break;
case '{':
return '}'; break;
default:
return 0; break;
}
}
};

GitHub测试程序源码