前言
今天是LeetCode打卡第五天,今天的题目是有效括号串,给定一个只包括 ‘(’,‘)’,‘{’,‘}’,‘[’,‘]’ 的字符串 s ,判断字符串是否有效。有效字符串需满足:
1.左括号必须用相同类型的右括号闭合。
2.左括号必须以正确的顺序闭合。
3.每个右括号都有一个对应的相同类型的左括号。
一、Python代码
class Vfhlist:
def __init__(self, aa):
self.aa = aa
self.list1 = []
def vfhlist(self):
for i in range(len(self.aa)):
if(self.aa[i] == '[' or self.aa[i] == '{' or self.aa[i] == '('):
self.list1.append(self.aa[i])
elif(self.aa[i] == ']'):
if(self.list1[-1] == '[' and len(self.list1) != 0):
self.list1.pop()
else:
print("这串括号不是有效符号")
return False
elif(self.aa[i] == '}'):
if(self.list1[-1] == '{' and len(self.list1) != 0):
self.list1.pop()
else:
print("这串括号不是有效符号")
return False
elif(self.aa[i] == ')'):
if(self.list1[-1] == '(' and len(self.list1) != 0):
self.list1.pop()
else:
print("这串括号不是有效符号")
return False
else:
print("里面的元素不全为括号")
return False
if(len(self.list1) == 0):
print("这是有效符号")
return True
if __name__ == "__main__":
aa = input("请输入括号:")
vv = Vfhlist(aa)
vv.vfhlist()
二、C++代码
1.头文件
#ifndef FHLIST_H
#define FHLIST_H
#include <stack>
#include <string>
class Fhlist
{
public:
void Vfhlist(std::string &b);
private:
std::stack<char> aa;
};
#endif
2.源代码
#include <iostream>
#include <stack>
#include "fhlist.h"
using namespace std;
void Fhlist::Vfhlist(string &b)
{
for(int i = 0; i < b.size(); i++)
{
switch(b[i])
{
case '[':
case '{':
case '(':
this->aa.push(b[i]);
break;
case ']':
if(!this->aa.empty() && this->aa.top() == '[') // 首先检查栈是否为空,否则会报错,空栈不支持.top()/.pop()
{
this->aa.pop();
}
else
{
cout << "不是有效符号" << endl;
return;
}
break;
case '}':
if(!this->aa.empty() && this->aa.top() == '{')
{
this->aa.pop();
}
else
{
cout << "不是有效符号" << endl;
return;
}
break;
case ')':
if(!this->aa.empty() && this->aa.top() == '(') // 检查栈是否为空
{
this->aa.pop();
}
else
{
cout << "不是有效符号" << endl;
return;
}
break;
default:
cout << "输入的不是括号串" << endl;
return;
}
}
if(this->aa.empty())
{
cout << "是有效符号" << endl;
}
else
{
cout << "不是有效符号" << endl;
}
}
3.执行代码
#include <iostream>
#include "fhlist.h"
#include <string>
#include <stack>
#include <sstream>
using namespace std;
int main()
{
stack<char> cc;
string xx = "" ;
char b;
cout << "请输入你的括号串:" ;
getline(cin, xx);
Fhlist LL;
LL.Vfhlist(xx);
return 0;
}
总结
今天的收获是熟悉了c++中数据容器栈stack的相关操作,再python中可以使用list列表代替栈的作用