leetcode 20 Valid Parentheses 括号匹配
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 括号匹配的更多相关文章
- 20. Valid Parentheses(括号匹配,用桟)
Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the inpu ...
- 20. Valid Parentheses - 括号匹配验证
Description: Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determin ...
- leetcode 20. Valid Parentheses 、32. Longest Valid Parentheses 、
20. Valid Parentheses 错误解法: "[])"就会报错,没考虑到出现')'.']'.'}'时,stack为空的情况,这种情况也无法匹配 class Soluti ...
- LeetCode 20 Valid Parentheses (括号匹配问题)
题目链接 https://leetcode.com/problems/valid-parentheses/?tab=Description Problem: 括号匹配问题. 使用栈,先进后出! ...
- [LeetCode] 20. Valid Parentheses 验证括号
Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the inpu ...
- [leetcode]20. Valid Parentheses有效括号序列
Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the inpu ...
- [LeetCode] 20. Valid Parentheses 合法括号
Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the inpu ...
- [LeetCode]20. Valid Parentheses有效的括号
Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the inpu ...
- leetCode 20.Valid Parentheses (有效的括号) 解题思路和方法
Valid Parentheses Given a string containing just the characters '(', ')', '{', '}', '[' and ']', de ...
随机推荐
- weblogic AND jboss 反序列化漏洞
C:\Program Files\Java\jboss-4.2.3.GA\server\default\deploy\http-invoker.sar\invoker.war\WEB-INF serv ...
- python序列化pickle/cPickle
一.pickle/Cpickle简介 Python序列化的概念很简单.内存里面有一个数据结构,你希望将它保存下来,重用,或者发送给其他人.你会怎么做?这取决于你想要怎么保存,怎么重用,发送给谁.很多游 ...
- E1
en表"使怎么样" engage 吸引,从事,订婚 be engaged in doing sth. 忙于 endure 忍耐,忍受 enforce 强制执行 enrol ...
- ACM Sudoku
Sudoku是一个非常简单的任务. 具有9行9列的方形表被划分为9个较小的正方形3x3,如图所示. 在一些单元格中写入从1到9的十进制数字.其他单元格为空. 目标是填充空单元格,其中十进制数字从1到9 ...
- Android 性能优化(一)内存篇
欢迎转载,转载请标明出处: http://blog.csdn.net/johnny901114/article/details/54377370 本文出自:[余志强的博客] 本博客同时也发布在 Hoo ...
- 一小时入门PHP
[版权申明:本文系作者原创,转载请注明出处] 文章出处:[http://blog.csdn.net/sdksdk0/article/details/52332296](http://blog.csdn ...
- Rails 4.0 bundle exec rspec spec/requests/xxx 测试失败的解决
rails项目没有使用默认的单元测试包,而是使用了rspec-rails来测试. 按照文档说明首先生成对应的测试文件: rails generate integration_test xxx invo ...
- gdb不知为何显示2次析构
gdb不知为何显示2次析构 (金庆的专栏 2016.11) gdb 显示2次 A::~A(): (gdb) bt #0 A::~A (this=0x602010, __in_chrg=<opti ...
- nginx时间设置解析函数
https://trac.nginx.org/nginx/browser/nginx/src/core/ngx_parse.c /* * Copyright (C) Igor Sysoev * Cop ...
- Visual Studio 写自己的动态链接库(DLL)
有些时候,我们想写自己的函数库以避免重复写代码,此文介绍如何使用Visual Studio编写自己的动态链接库. 0,实验环境说明: 集成开发环境:Visual Studio 10.0 操作系统: W ...