描述

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.

分析

遇到这种括号匹配的问题,当然要用栈来写。先把string的第一个元素压入栈,再从第二个元素开始遍历,如果栈顶元素为和当前string的元素相匹配,就把该元素出栈。如果在遍历期间堆栈为空了,比如输入的是:

[]{}()

那么在i=1的时候栈就会为空,这时候取栈顶元素是没有意义的。因此如果遍历期间发现栈为空,就直接把当前的string元素压入栈中。

另外,如果输入的string的长度不是偶数,那么肯定是不匹配的,在一开始的时候做这个判断,可以筛掉很多种不匹配的情况。

总之,如果输入的string是匹配的,那么最终的栈一定为空。

为了判断栈顶元素和当前string的元素是否相匹配,可以定义一个名为isOK的函数。

代码如下:

class Solution {
public:
bool isOK(const char &a,const char &b){
if((a == '(' && b == ')')
|| (a == '[' && b == ']')
|| (a == '{' && b == '}'))
return true;
else
return false; }
bool isValid(string s) {
if(s.size() % 2 != 0)return false;
stack<char>sc;
sc.push(s[0]);
for(int i = 1; i != s.size(); ++i){
if(sc.empty())
sc.push(s[i]);
else{
if(isOK(sc.top(),s[i]))
sc.pop();
else
sc.push(s[i]);
}
}
return sc.empty();
}
};

下面是另一种更优雅的解法:

https://leetcode.com/problems/valid-parentheses/#/solutions

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

leetcode解题报告(7):Valid Parentheses的更多相关文章

  1. LeetCode解题报告—— Longest Valid Parentheses

    Given a string containing just the characters '(' and ')', find the length of the longest valid (wel ...

  2. LeetCode解题笔记 - 20. Valid Parentheses

    这星期听别人说在做LeetCode,让他分享一题来看看.试了感觉挺有意思,可以培养自己的思路,还能方便的查看优秀的解决方案.准备自己也开始. 解决方案通常有多种多样,我觉得把自己的解决思路记录下来,阶 ...

  3. LeetCode解题报告:Linked List Cycle && Linked List Cycle II

    LeetCode解题报告:Linked List Cycle && Linked List Cycle II 1题目 Linked List Cycle Given a linked ...

  4. 乘风破浪:LeetCode真题_032_Longest Valid Parentheses

    乘风破浪:LeetCode真题_032_Longest Valid Parentheses 一.前言 这也是非常有意思的一个题目,我们之前已经遇到过两个这种括号的题目了,基本上都要用到堆栈来解决,这次 ...

  5. leetcode解题报告(2):Remove Duplicates from Sorted ArrayII

    描述 Follow up for "Remove Duplicates": What if duplicates are allowed at most twice? For ex ...

  6. leetcode解题报告 32. Longest Valid Parentheses 用stack的解法

    第一道被我AC的hard题!菜鸡难免激动一下,不要鄙视.. Given a string containing just the characters '(' and ')', find the le ...

  7. LeetCode 解题报告索引

    最近在准备找工作的算法题,刷刷LeetCode,以下是我的解题报告索引,每一题几乎都有详细的说明,供各位码农参考.根据我自己做的进度持续更新中......                        ...

  8. 【一天一道LeetCode】#32. Longest Valid Parentheses

    一天一道LeetCode系列 (一)题目 Given a string containing just the characters '(' and ')', find the length of t ...

  9. 【LeetCode练习题】Longest Valid Parentheses

    Longest Valid Parentheses Given a string containing just the characters '(' and ')', find the length ...

  10. [Leetcode][Python]32: Longest Valid Parentheses

    # -*- coding: utf8 -*-'''__author__ = 'dabay.wang@gmail.com' 32: Longest Valid Parentheseshttps://oj ...

随机推荐

  1. linux上启动tomcat报错:Failed to read schema document 'http://www.springframework.org/schema/data/mongo/spring-mongo-2.0.xsd

    本文原文连接: http://blog.csdn.net/bluishglc/article/details/7596118 ,转载请注明出处! spring在加载xsd文件时总是先试图在本地查找xs ...

  2. Tokitsukaze and Strange Rectangle CodeForces - 1191F (树状数组,计数)

    大意: 给定$n$个平面点, 定义集合$S(l,r,a)$表示横坐标$[l,r]$纵坐标$[a,\infty]$内的所有点. 求可以得到多少种不同的集合. 从上往下枚举底层最右侧点, 树状数组统计贡献 ...

  3. SSL Virtual Servers

    SSL Virtual Servers 来源 https://www.carlstalhood.com/ssl-virtual-servers-netscaler-12/ SSL Virtual Se ...

  4. Java中的ThreadLocal详解

    一.ThreadLocal简介 多线程访问同一个共享变量的时候容易出现并发问题,特别是多个线程对一个变量进行写入的时候,为了保证线程安全,一般使用者在访问共享变量的时候需要进行额外的同步措施才能保证线 ...

  5. Vue路由相关配置

    什么是路由? 1.在以前页面跳转使用的是超链接a标签或者js location.href,而路由是跳转切换组件的跳转方式 2.路由就是监听url的改变并提供相对应的组件用于展示 3.vue-route ...

  6. 建表时表空间的一些参数pctfree initrans maxtrans storage的含义

    转自:https://a475334705.iteye.com/blog/2291441 create table X_SMALL_AREA (   idx_id             NUMBER ...

  7. leetcode-63. Unique Paths II · DP + vector

    题面 A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). ...

  8. KVM之virsh管理虚拟机网卡配置

    虚拟机网卡管理 virsh attach-interface 添加网卡: [root@ubuntu ~]# virsh domiflist CentOS-V6.5.23-server01 Interf ...

  9. MySQL操作规范总结

    来源:静以致远√团团 用户权限管理创建用户命令:CREATE USER 'username'@'host' IDENTIFIED BY 'password';说明:Username所创建的用户名hos ...

  10. CentOS 7 配置VNCServer

    因为一直在用xmanager ,所以CentOS 7 上没过VNCSserver了,最近安装Oracle19C ,xmanager 总是卡死,所以配置VNC. 发现仅仅yum install -y t ...