**题目描述:**给定一个只包括’(’,’)’,’{’,’}’,’[’,’]'的字符串,判断字符串是否有效。
有效字符串需满足:
1、左括号必须用相同类型的右括号闭合;
2、左括号必须以正确的顺序闭合。
注:空字符串可被认为有效字符串
示例1:
输入:“()”
输出:true
示例2:
输入:“()[]{}"
输出:true
示例3:
输入:"(]"
输出:false
示例4:
输入:"([)]"
输出:false
示例5:
输入:"{[]}"
输出:true
代码:(C++实现)
#include<stdio.h>
#include<stack>
#include<iostream>
using namespace std;
class Solution {
public:
/*
*stack<DataType> s;
*s.empty();//如果栈为空则返回true,否则返回false
*s.size();//返回栈中元素的个数
*s.top();//返回栈顶元素,但不删除该元素
*s.pop();//弹出栈顶元素,但不返回其值
*s.push();//将元素压入栈顶
*/
bool isValid(string s) {
if (s.size() % 2 == 1) {
cout << "false" << endl;
return false;
}
stack<char> elementIn;
for (int i = 0; i<s.size(); i++) {
elementIn.push(s[i]);
}
stack<char> elementOut;
while (elementIn.size()) {//求栈中元素个数使用s.size()函数
if (elementOut.empty()) {//判断是否为空使用s.empty()函数
//s.top();返回栈顶元素,但不删除该元素
//s.pop();弹出栈顶元素,但不返回其值
elementOut.push(elementIn.top());//将1号栈顶元素的值取出,并压入2号栈顶
elementIn.pop();//直接将栈顶元素删除
}
char top1 = elementIn.top();//返回1号栈顶元素
char top2 = elementOut.top();//返回2号栈顶元素
if ((top1 == '('&&top2 == ')') || (top1 == '['&&top2 == ']') || (top1 == '{'&&top2 == '}')) {
elementIn.pop();
elementOut.pop();
}
else {
elementOut.push(elementIn.top());
elementIn.pop();
}
}
if (!elementOut.empty()) {
cout << "false" << endl;
return false;
}
else {
cout << "true" << endl;
return true;
}
}
};
int main() {
Solution a;
a.isValid("([])");
system("pause");
return 0;
}
运行结果: