描述

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. node 标准输入流和输出流

    使用node 在 CMD 控制台获取输入的指令: 方式一: process.stdin.resume(); process.stdin.setEncoding('utf-8'); process.st ...

  2. 巧用Ajax的beforeSend 提高用户体验--防止重复数据

    巧用Ajax的beforeSend 提高用户体验 jQuery是经常使用的一个开源js框架,其中的$.ajax请求中有一个beforeSend方法,用于在向服务器发送请求前执行一些动作.具体可参考jQ ...

  3. JDBC 复习4 批量执行SQL

    1使用jdbc进行批量执行SQL在实际的项目开发中,有时候需要向数据库发送一批SQL语句执行,这时应避免向数据库一条条的发送执行,而应采用JDBC的批处理机制,以提升执行效率. package dbe ...

  4. python基础之迭代器协议和生成器(一)

    一 递归和迭代 二 什么是迭代器协议 1.迭代器协议是指:对象必须提供一个next方法,执行该方法要么返回迭代中的下一项,要么就引起一个StopIteration异常,以终止迭代 (只能往后走不能往前 ...

  5. SSRF(服务端请求伪造)

  6. Python 遍历文件夹清理磁盘案例

    import os suffix_name_list = [".pdb", ".ilk"] def find_file(path): # 遍历文件夹 for i ...

  7. linux命令启动关闭firewalld防火墙,添加端口

    firewalld管理防火墙常用命令   1.查看防火墙的状态 [root@localhost HMK]# firewall-cmd --state 查看防火墙的运行状态 not running [r ...

  8. c#创建目录和文件夹,数据写入并生成txt文件

    c#创建目录: // 获取程序的基目录.System.AppDomain.CurrentDomain.BaseDirectory // 获取模块的完整路径.System.Diagnostics.Pro ...

  9. 【Day5】项目实战.CSDN热门文章爬取

    import urllib.request as ur import lxml.etree as le import user_agent keyword = input('请输入关键词:') pn_ ...

  10. 初级文件IO——IO过程、open、close、write、read、lseek、dup、dup2、errno、perror

    先要回答的问题 文件IO指的是什么? 本文主要讲述如何调用Linux OS所提供的相关的OS API,实现文件的读写. 如何理解文件IO? IO就是input output的意思,文件io就是文件输入 ...