尧图网站设计 尧图网站设计YAOTU DESIGN
ARTICLE DETAIL

资讯详情

深耕网站设计与一线实操的经验洞察。

打卡18:有效括号

打卡18:有效括号 题目链接https://leetcode.cn/problems/valid-parentheses/ 视频讲解https://www.bilibili.com/video/BV1AF411w78g核心思路遇到左括号入栈遇到右括号时检查栈顶是否匹配。#include stdbool.h #include string.h bool isValid(char* s) { int n strlen(s); char stack[n]; // 用数组模拟栈最大长度即字符串长度 int top -1; // 栈顶指针-1 表示空栈 for (int i 0; s[i] ! \0; i) { char ch s[i]; if (ch ( || ch [ || ch {) { stack[top] ch; // 左括号入栈 } else { if (top -1) return false; // 栈空没有匹配的左括号 char left stack[top--]; // 弹出栈顶 if ((ch ) left ! () || (ch ] left ! [) || (ch } left ! {)) { return false; // 括号不匹配 } } } return top -1; // 栈空则所有括号正确闭合 }
返回列表