有效的括号:
给定一个只包括 ‘(’,‘)’,‘{’,‘}’,‘[’,‘]’ 的字符串 s ,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
#include <iostream>
#include <stack>
#include <cassert>
using namespace std;
// 20. Valid Parentheses
// https://leetcode.com/problems/valid-parentheses/description/
// 时间复杂度: O(n)
// 空间复杂度: O(n)
class Solution {
public:
bool isValid(string s) {
stack<char> stack;
for( int i = 0 ; i < s.size() ; i ++ )
if( s[i] == '(' || s[i] == '{' || s[i] == '[')
stack.push(s[i]);
else{
if( stack.size() == 0 )
return false;
char c = stack.top();
stack.pop();
char match;
if( s[i] == ')' )
match = '(';
else if( s[i] == ']' )
match = '[';
else{
assert( s[i] == '}' );
match = '{';
}
if(c != match)
return false;
}
if( stack.size() != 0 )
return false;
return true;
}
};
int main() {
if(Solution().isValid("()"))
cout << "() is valid." << endl;
else
cout << "() is invalid." << endl;
if(Solution().isValid("()[]{}"))
cout << "()[]{} is valid." << endl;
else
cout << "()[]{} is invalid." << endl;
if(Solution().isValid("(]"))
cout << "(] is valid." << endl;
else
cout << "(] is invalid." << endl;
if(Solution().isValid("([)]"))
cout << "([)] is valid." << endl;
else
cout << "([)] is invalid." << endl;
return 0;
}