2023每日刷题(二十七)
Leetcode—20.有效的括号
C++实现代码
class Solution {
public:
bool isValid(string s) {
stack<char> arr;
int len = s.size();
if(len == 1) {
return false;
}
for(int i = 0; i < len; i++) {
if(s[i] == '(' || s[i] == '[' || s[i] == '{') {
arr.push(s[i]);
} else {
if(arr.empty()) {
return false;
}
char t = s[i];
char pairBracket = ' ';
switch(t) {
case ')':
pairBracket = '(';
break;
case ']':
pairBracket = '[';
break;
case '}':
pairBracket = '{';
break;
}
if(arr.top() != pairBracket) {
return false;
} else {
arr.pop();
}
}
}
if(arr.empty()) {
return true;
}
return false;
}
};
运行结果
C语言实现代码
#define MAXSIZE 10003
typedef struct {
char data[MAXSIZE];
int top;
}SqStack;
void InitStack(SqStack *st) {
st->top = -1;
}
bool stackEmpty(SqStack st) {
return st.top == -1;
}
bool Push(SqStack *st, char e) {
if(st->top == MAXSIZE - 1) {
return false;
}
st->top++;
st->data[st->top] = e;
return true;
}
char Pop(SqStack *st) {
char e = st->data[st->top];
st->top--;
return e;
}
char getTop(SqStack st) {
return st.data[st.top];
}
bool isValid(char* s) {
SqStack st;
InitStack(&st);
int n = strlen(s);
for(int i = 0; i < n; i++) {
if(s[i] == '(' || s[i] == '[' || s[i] == '{') {
Push(&st, s[i]);
} else {
if(stackEmpty(st)) {
return false;
}
char t = s[i];
char pairBracket = ' ';
switch(t) {
case ')':
pairBracket = '(';
break;
case ']':
pairBracket = '[';
break;
case '}':
pairBracket = '{';
break;
}
if(getTop(st) != pairBracket) {
return false;
} else {
Pop(&st);
}
}
}
if(stackEmpty(st)) {
return true;
}
return false;
}
运行结果
之后我会持续更新,如果喜欢我的文章,请记得一键三连哦,点赞关注收藏,你的每一个赞每一份关注每一次收藏都将是我前进路上的无限动力 !!!↖(▔▽▔)↗感谢支持!