题目描述
https://leetcode-cn.com/problems/valid-parentheses/
思路
- 栈解法,遇到左括号压入栈中,遇到右括号与栈顶元素进行配对,配对成功弹出栈顶元素,配对失败返回false
- 需要注意只有右括号的情况
AC代码
#include <iostream>
#include <string>
#include <stack>
using namespace std;
class Solution
{
public:
bool isValid(string s)
{
if (s == "")
return true;
if (s.size() % 2)
return false;
stack<char> temp;
for (int i = 0; i < s.size(); i++)
{
if (!temp.empty()) //需要注意只有右括号的情况
{
if (s[i] == '(' || s[i] == '{' || s[i] == '[')
temp.push(s[i]);
else
{
//()差1,{}[]差2
if (s[i] == temp.top() + 1 || s[i] == temp.top() + 2)
temp.pop();
else
return false;
}
}
else
temp.push(s[i]);
}
return temp.size()==0;
}
};
int main()
{
// cout << "hellp world" << endl;
string s = "()";
Solution so;
cout << so.isValid(s);
return 0;
}