给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。
#include<stack>
//{}[]()
//时间复杂度为o(n)空间复杂度为o(n)
bool match(string matchstr)
{
std::stack<char> m_stak;
for (int i = 0; i < matchstr.length(); i++) {
if (matchstr[i] == '(' ||
matchstr[i] == '[' ||
matchstr[i] == '{') {
m_stak.push(matchstr[i]);
continue;
}
if (!m_stak.empty() && (
(matchstr[i] == ')' && m_stak.top() == '(') ||
(matchstr[i] == ']' && m_stak.top() == '[') ||
(matchstr[i] == '}' && m_stak.top() == '{'))) {
m_stak.pop();
}
else {
return false;
}
}
return m_stak.empty() ? true : false;
}
对于单一种类的括号,比如只有()括号对,那么算法可以优化,使其空间复杂度变为o(1):
//单括号()
//时间复杂度为o(n)空间复杂度为o(1)
bool singleMatch(string matchstr)
{
int m_count = 0;
for (int i = 0; i < matchstr.length(); i++) {
if (matchstr[i] == '(') {
m_count++;
continue;
}
if (matchstr[i] == ')') m_count--;
if (m_count < 0)
return false;
}
return m_count == 0 ? true : false;
}