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 ...
随机推荐
- chrome下positon:fixed无效或抖动的解决办法
先来看一下我们要实现的效果 我想这种效果大家都有实现过,或者说吸顶的效果和这差不多 页面结构 js代码如下 /*吸顶*/ var $child = $("#child_3"); v ...
- js密码64加密
可以在客户端对密码进行简单的64位加密,服务端对应使用64位解密即可. /** * * Base64 encode / decode * * @author * @date * @email */ f ...
- 使用 OpenCV 与 Face++ 人脸识别
今天看到一篇文章<使用 OpenCV 与 Face++ 实现人脸解锁>,感觉挺好玩,就照着作者的讲解,写了一下.详细内容还请看原作者文章. # *^_^* coding:utf-8 *^_ ...
- ubuntu下安装 python 常用软件
1.用于科学计算的常用包: sudo apt-get install python-numpy python-scipy python-matplotlib ipython ipython-noteb ...
- Android POJO 转换器 —> RapidOOO
博客搬迁至https://blog.wangjiegulu.com RSS订阅:https://blog.wangjiegulu.com/feed.xml 原文链接:https://blog.wang ...
- ACM Robot Motion
机器人已被编程为按照其指令中的路径进行操作.机器人要移动的下一个方向的指令放在网格中.可能的指令是 N north (up the page) S south (down the page) E ...
- django模板语言中的extends,block和include
extends和block一起用 它们用于母版和子版的继承 在母版html中将一些需要替换的部分用{% block xxx %}...{% endblock %}括起来, 在子版html中,在第一行需 ...
- Java中的泛型类和泛型方法区别和联系
泛型的概念大家应该都会,不懂的百度或者google,在java中泛型类的定义较为简单 <span style="font-size:18px;"><span st ...
- 大数据基础知识问答----hadoop篇
handoop相关知识点 1.Hadoop是什么? Hadoop是一个由Apache基金会所开发的分布式系统基础架构.用户可以在不了解分布式底层细节的情况下,开发分布式程序.充分利用集群的威力进行高速 ...
- SQLite 语法(http://www.w3cschool.cc/sqlite/sqlite-syntax.html)
SQLite 语法 SQLite 是遵循一套独特的称为语法的规则和准则.本教程列出了所有基本的 SQLite 语法,向您提供了一个 SQLite 快速入门. 大小写敏感性 有个重要的点值得注意,SQL ...