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.

写了一个0ms 的代码:

// 20150630.cpp : 定义控制台应用程序的入口点。
// #include "stdafx.h"
#include <iostream>
#include <stack>
#include <string>
using namespace std; bool isValid(string s)
{
if (s=="")return false; stack<char> Parentheses;
int size =s.size(); Parentheses.push(s[0]); for(int i = 1;i < size ;++i)
{ if(Parentheses.top()=='('&&s[i]==')'||Parentheses.top()=='['&&s[i]==']'||Parentheses.top()=='{'&&s[i]=='}')
{
Parentheses.pop();
if (Parentheses.empty()&&(i+1)!=size)
{
Parentheses.push(s[i+1]);
i++;
}
} else
{
Parentheses.push(s[i]);
} } if(Parentheses.empty())
{
return true;
}
else
{
return false;
}
}
int _tmain(int argc, _TCHAR* argv[])
{
string s = "()[]{}";
isValid(s);
return 0;
}

另外一个看着好看点的:

class Solution {
public:
bool isValid(string s)
{
std::stack<char> openStack;
for(int i = 0; i < s.length(); i++)
{
switch(s[i])
{
case '(':
case '{':
case '[':
openStack.push(s[i]);
break;
case ')':
if(!openStack.empty() && openStack.top() == '(' )
openStack.pop();
else
return false;
break;
case '}':
if(!openStack.empty() && openStack.top() == '{' )
openStack.pop();
else
return false;
break;
case ']':
if(!openStack.empty() && openStack.top() == '[' )
openStack.pop();
else
return false;
break; default:
return false;
}
} if(openStack.empty())
return true;
else
return false;
}
};

python代码:

class Solution:
# @return a boolean
def isValid(self, s):
stack = []
dict = {"]":"[", "}":"{", ")":"("}
for char in s:
if char in dict.values():
stack.append(char)
elif char in dict.keys():
if stack == [] or dict[char] != stack.pop():
return False
else:
return False
return stack == []

</pre><pre class="python" name="code">class Solution:
# @param s, a string
# @return a boolean
def isValid(self, s):
paren_map = {
'(': ')',
'{': '}',
'[': ']'
}
stack = [] for p in s:
if p in paren_map:
stack.append(paren_map[p])
else:
if not stack or stack.pop() != p:
return False return not stack

class Solution:
# @param s, a string
# @return a boolean
def isValid(self, s):
d = {'(':')', '[':']','{':'}'}
sl = []
for i in s:
if i in d:
sl.append(i)
else:
if not sl or d[sl.pop()] != i:
return False if sl:
return False
return True



leetcode 20 Valid Parentheses 括号匹配的更多相关文章

  1. 20. Valid Parentheses(括号匹配,用桟)

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

  2. 20. Valid Parentheses - 括号匹配验证

    Description: Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determin ...

  3. leetcode 20. Valid Parentheses 、32. Longest Valid Parentheses 、

    20. Valid Parentheses 错误解法: "[])"就会报错,没考虑到出现')'.']'.'}'时,stack为空的情况,这种情况也无法匹配 class Soluti ...

  4. LeetCode 20 Valid Parentheses (括号匹配问题)

    题目链接 https://leetcode.com/problems/valid-parentheses/?tab=Description   Problem: 括号匹配问题. 使用栈,先进后出!   ...

  5. [LeetCode] 20. Valid Parentheses 验证括号

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

  6. [leetcode]20. Valid Parentheses有效括号序列

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

  7. [LeetCode] 20. Valid Parentheses 合法括号

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

  8. [LeetCode]20. Valid Parentheses有效的括号

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

  9. leetCode 20.Valid Parentheses (有效的括号) 解题思路和方法

    Valid Parentheses  Given a string containing just the characters '(', ')', '{', '}', '[' and ']', de ...

随机推荐

  1. Mysql数据库连接报错!1130:host XXX is not allowed to connect to this mysql server

    我猜想是可能是连接的用户权限问题.结果这样子操作mysql库,可以解决此问题.在本机登入mysql后,更改 “mysql” 数据库里的 “user” 表里的 “host” 项,从”localhost” ...

  2. net框架运行原理

    核心是CLR(通用语言运行时), c#或者其它各种语言编译原理:将原代码通过相对的编译器(语法检查原代码分析)生成IL代码托管(IL也称托管代码),最后得到一个托管模块,一个或多个托管模块组成程序集( ...

  3. python笔记一(语言简介、解释器、输入输出)

    一.python语言简介 一顿狂吹python目前有多火.多NB,哈哈哈,不过用起来心情确实很舒畅. 解释性语言:缺点,运行速度慢. 二.python解释器 与C.C++.java不同,以上都需要先将 ...

  4. ng-book札记——路由

    路由的作用是分隔应用为不同的区块,每个区块基于匹配当前URL的规则. 路由可以分为服务端与客户端两种,服务端以Express.js为例: var express = require('express' ...

  5. Java不走弯路教程(3.用户验证与文件内容查询)

    3.用户验证与文件内容查询 在上一章中,我们完成了对指定文件内容的输出操作. 我们现在有如下格式的文件product.db id,product_name,product_detail 1,noteb ...

  6. PHP $_POST 变量

    $_POST 变量 预定义的 $_POST 变量用于收集来自 method="post" 的表单中的值. 从带有 POST 方法的表单发送的信息,对任何人都是不可见的(不会显示在浏 ...

  7. Dynamics 365 Web Api之基于single-valued navigation property的filter查询

    本篇要讲的是dynamics 新版本中web api的一个改进功能,虽然改进的很有限,但至少是改进了. 举个例子,我们现在知道联系人的名字vic,我们想找出客户记录中主要联系人名字为vic的所有客户, ...

  8. Swift类中如何创建一个对外只读对内可读写的属性

    很简单用private修饰符,后面跟限制关键字set: class Day{ private(set) var rawValue:Int = 0 func showRawValue(){ print( ...

  9. 说一说关于破解支付宝AR红包的事

    当朋友圈的你们才开始分享支付宝AR红包的消息的时候,我已经对它动了一二三四次歪脑筋了,虽然事实证明并不是那么顺利,至今我也只在电脑前识别出5个不知道在哪里的红包,其中一个还因为定位信息不符开不了. 昨 ...

  10. Web自动化框架LazyUI使用手册(5)--模板工程:LazyUI-template详解

    概述: LazyUI-template: 提供Maven管理的,基于Spring+Testng的,包含常用浏览器driver的,方便连接各种数据库的java模板工程,并提供以百度搜索为例的第一个测试用 ...