给定一个只包括 ‘(’,’)’,’{’,’}’,’[’,’]’ 的字符串,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。 左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。
来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/valid-parentheses
采用vector的方法进行
想法:设计主函数和一个类,输入字符串即可实现相关功能
将class放在一个.h文件里,将其功能进行封装
**遇到问题1:**class的写入。
类的写入注意:
1)头文件包含了如#include则在class的.h文件不需要再次写入,同理(都写入头文件也不会报错,两个写入一个即可)
2)对于std空间函数,用到的话要将其写入,否则额会报错
//这个代码怎么写都是错的,始终返回0。需要重写,但要找出错误
class Solution {
public:
bool isValid(string s);
};
using namespace std;
bool Solution::isValid(string s)
{
int n = s.length();
char right;
int temp;
vector<char>left;
if (n % 2 == 0)
{
for (int i = 0; i < n; i++)
{
if ((s[i] == '(') && (s[i] == '[') && (s[i] == '{'))//**与运算时“&&”不是“&”**
{
left.push_back(s[i]);
}
else
{
right = s[i];
temp = left.size();
if (temp == 0)return 0;
if (((right == ')') && (left[temp - 1] == '(')) || ((right == '[') && (left[temp - 1] == ']')) || ((right == '}') && (left[temp - 1] == '{')))
{
left.pop_back();
}
else return 0;
}
}
int num = left.size();
if (num == 0)
{
return 1}
else return 0;
}
else return 0;
};
下面是修改后的:
using namespace std;
bool Solution::isValid(string s)
{
int n = s.length();
char right;
int count;
vector<char>left;
if (n % 2 == 0 && s[0] != ')' && s[0] != ']' && s[0] != '}')
{
for (int i = 0; i < n; i++)
{
if (s[i] == '(' || s[i] == '[' || s[i] == '{')
{
left.push_back(s[i]);
}
else
{
count = left.size();
right = s[i];
char temp = left[count - 1];
if ((temp == '(' && right == ')') || (temp == '[' && right == ']') || (temp == '{' && right == '}'))
{
left.pop_back();
}
else return 0;
}
}
int num = left.size();
if (num == 0)
{
return 1;
}
else return 0;
}
else return 0;
};