【POJ HDOJ leetcode】括号匹配合法性及最长括号匹配
/*
1. string parenthesis
给出一个由()组成的字符串判断合法性,如()合法, (, (((不合法.
2. 给出一串()字符串,求出最长连续括号匹配的长度及其位置
*/
#include <iostream> #include <stdio.h> #include <stack> using namespace std; class Solution { public: bool isValid(const string& s) { if (s == "") { return true; } stack<char> stk; size_t size = s.size(); for (size_t i = 0; i < size; i++) { if (s[i] == '(') { stk.push(s[i]); } else { if (stk.empty()) return false; stk.pop(); } } return stk.size() == 0; } }; pair<int,int> NumOfMatch(const char* str) { if (str == NULL) return {0, 0}; const char* p = str; int nLeft = 0; // 待匹配的左括号的个数 int nMatchedPre = 0;// 上一个匹配子串的已匹配括号的对数 int nMatchedCur = 0;// 当前子串的已匹配括号的对数 int maxi = -1, maxmatch = 0; const char* front = p; while (*p != '\0') { if (*p == '(') { ++nLeft; } else if (*p == ')') { if (nLeft == 0) { maxmatch = max(nMatchedCur, maxmatch); nMatchedPre = nMatchedCur; nMatchedCur = 0; } else { nMatchedCur++; nLeft--; if (nMatchedCur > maxmatch) { maxi = (p - front); maxmatch = nMatchedCur; } } } p++; } maxi -= maxmatch * 2 - 1; maxmatch *= 2; return make_pair(maxi, maxmatch); } int cnt = 0; int total = 0; void expect_test(bool a, bool b) { total++; if (a == b) { cnt++; return; } printf("expect %d actual %d\n", a, b); } void expect_test_int(int a, int b) { total++; if (a == b) { cnt++; return; } printf("expect %d actual %d\n", a, b); } typedef pair<int,int> pii; void expect_test_pair(pii a, pii b) { total++; if (a.first == b.first && a.second == b.second) { cnt++; return; } printf("expect {%d,%d} actual {%d,%d}\n", a.first, a.second, b.first, b.second); } int main() { Solution sol; expect_test(true, sol.isValid("()")); expect_test(true, sol.isValid("(())")); expect_test(true, sol.isValid("()()")); expect_test(false, sol.isValid(")")); expect_test_pair({0, 2}, NumOfMatch("()))")); expect_test_pair({0, 4}, NumOfMatch("(()))")); expect_test_pair({0, 4}, NumOfMatch("(())")); expect_test_pair({0, 0}, NumOfMatch("")); expect_test_pair({4, 4}, NumOfMatch("())((())")); printf("%d/%d\n", cnt, total); return 0; }
分类:
算法竞赛+iGEM
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
2017-08-18 一个大规模爬虫的抓取实例