描述

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. 【转载】【最短路Floyd+KM 最佳匹配】hdu 2448 Mining Station on the Sea

    Mining Station on the Sea Problem Description The ocean is a treasure house of resources and the dev ...

  2. (十一)web服务与javaweb结合(2)

    一.解决问题及解决方法 解决问题:上章节用监听器的方式是有缺陷的:web服务的端口和web工程的端口不能一致. 解决方案:将webService绑定到web工程中,使得共用一个端口. 二.案例 2.1 ...

  3. 数据库及MySQL基础(1)

    1.数据库概述 关系型数据库:面对关系,Java面向对象. ·常见数据库 Oracle(神喻):甲骨文 DB2:IBM SQL Server:微软 Sybase:赛尔斯 MySQL:甲骨文,最早是开源 ...

  4. Windows 下 mysql 5.7 设置 区分大小写(敏感),设置默认编码 utf8mb4

    修改编码 c盘下搜索 C:\ProgramData\MySQL\MySQL Server 5.7 在该my.ini文件下进行配置修改 [client] default-character-set = ...

  5. css3 transform实现水平和垂直居中

    代码如下: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF ...

  6. js中undefined的几种情况

    1.变量声明且没有赋值: 2.获取对象中不存在的属性时: 3.函数需要实参,但是调用时没有传值,形参是undefined: 4.函数调用没有返回值或者return后没有数据,接收函数返回的变量是und ...

  7. Java 之 可变参数

    可变参数 在JDK1.5之后,如果我们定义一个方法需要接受多个参数,并且多个参数类型一致,我们可以对其简化成如下格式: 修饰符 返回值类型 方法名(参数类型... 形参名){ } 其实这个书写完全等价 ...

  8. 用cef Python打造自己的浏览器

    背景 项目需要做一个客户端的壳,内置浏览器,访问指定 的url 采用技术 python3.5 cefpython https://github.com/cztomczak/cefpython#inst ...

  9. Linux Backup: Hard Disk Clone with "dd"

      Most of Windows users may know "Norton Ghost". Norton Ghost is a backup software for har ...

  10. java中的管程

    前言 ​ 并发编程这个技术领域已经发展了半个世纪了,相关的理论和技术纷繁复杂.那有没有一种核心技术可以很方便地解决我们的并发问题呢?这个问题如果让我选择,我一定会选择管程技术.Java 语言在 1.5 ...