博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
括号匹配问题
阅读量:7225 次
发布时间:2019-06-29

本文共 2063 字,大约阅读时间需要 6 分钟。

1.简单括号的匹配

Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.

用数据结构栈即可完成算法

class Solution {public:    bool isValid(string s) {       stack
paren; for (char& c : s) { switch (c) { case '(': case '{': case '[': paren.push(c); break; case ')': if (paren.empty() || paren.top() != '(') return false; else paren.pop(); break; case '}': if (paren.empty() || paren.top() != '{') return false; else paren.pop(); break; case ']': if (paren.empty() || paren.top() != '[') return false; else paren.pop(); break; default:; // pass } } return paren.empty(); }};

2.产生括号匹配

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

For example, given n = 3, a solution set is:

[

"((()))",
"(()())",
"(())()",
"()(())",
"()()()"]

产生括号经典的方法就是回溯

class Solution {public:    void backtrack(vector
&res,string s,int open,int close,int n) { if(s.size()==2*n) { res.push_back(s); return; } if(open
generateParenthesis(int n) { vector
res; backtrack(res,"",n,0); return res; }};

3.最长括号匹配

Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.

For "(()", the longest valid parentheses substring is "()", which has length = 2.

Another example is ")()())", where the longest valid parentheses substring is "()()", which has length = 4.

这个方法即是把匹配不上的两个括号储存在stack中,最后再比较两个的大小

注意从-1的位置到第一个未匹配的括号还是要比较的,所以就有了 res=max(res,b); 这一句

class Solution {public:    int longestValidParentheses(string s) {        stack
m; for(int i = 0;i
b-a-1?res:b-a-1; }};

转载于:https://www.cnblogs.com/vhyz/p/8680525.html

你可能感兴趣的文章
nethogs监控进程网络流量
查看>>
LinkedHashSet 元素唯一,存储取出有序
查看>>
!!!四种常见的 POST 提交数据方式(含application/json)
查看>>
vim的用法简介
查看>>
Docker快速入门
查看>>
Linux运维常见面试题之精华收录
查看>>
Open Source的一些网站,自己收集来的
查看>>
导入ubuntu虚机配置,基于XEN4.0
查看>>
Script:收集UNDO诊断信息
查看>>
jmeter连接数据库-华山
查看>>
opencv 源码编译
查看>>
将旧硬盘的内容克隆到新硬盘
查看>>
Linux文件管理类命令之rm
查看>>
如何在Kubernetes中暴露服务访问
查看>>
NTP常见问题和解决方案&配置文件详解
查看>>
crontab计划任务补充知识
查看>>
数据库备份
查看>>
独家 | 图灵奖得主Raj Reddy:通用AI还很遥远,人类将成宠物
查看>>
java中自动生成XML文件
查看>>
Docker 数据卷,数据卷容器详细介绍
查看>>