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 ...
随机推荐
- 将jdbc连接明文密码加密方案
最近没有及时写文章,把最近处理的几个问题集中了一下写出来.这篇文章是关于如何处理spring项目中引入数据库连接等 使用的用户名和密码的明文进行加密.防止被他人窃取利用. 我们选择的加密方式为DES加 ...
- 70. Climbing Stairs(easy, 号称 Dynamic Programming 天下第一题)
You are climbing a stair case. It takes n steps to reach to the top. Each time you can either climb ...
- Vue实践经验
多考虑应变 如果模版中绑定了 obj.xx 时,需要注意 obj 是否是异步数据,默认值是否为 null.安全起见,可在组件最外层加 v-if 判断. <template> <div ...
- IP地址段遍历
#region 搜索ftp服务器地址 /// <summary> /// 搜索ftp服务器 /// </summary> public void SearchFtpServer ...
- Dubbo介绍和服务架构分析
Dubbo是阿里巴巴公司开源的一个高性能优秀的服务框架,使得应用可通过高性能的 RPC 实现服务的输出和输入功能,可以和Spring框架无缝集成.使用zookeeper作为服务的注册中心,对外提供服务 ...
- 基于无域故障转移群集 配置高可用SQLServer 2016数据库
基于上次的文章搭建的环境,可以在这里:http://www.cnblogs.com/DragonStart/p/8275182.html看到上次的文章. 演示环境 1. 配置一览 Key Value ...
- R语言中函数调试
有时候会用R语言写一下简单的脚本处理函数,加入需要调试的话可以按照下面的步骤进行: fun <- function(x , y){ x + y x - y x * y x / y } debug ...
- PHP 5 Filesystem 函数
PHP Filesystem 简介 Filesystem 函数允许您访问和操作文件系统. 安装 Filesystem 函数是 PHP 核心的组成部分.无需安装即可使用这些函数. Runtime 配置 ...
- Docker的Fig 项目
在你的应用里面添加一个 fig.yml 文件,并指定一些简单的内容,执行 fig up 它就能帮你快速建立起一个容器 快速搭建基于 Docker 的隔离开发环境 使用 Dockerfile 文件指定你 ...
- 更快实现Android多级树形选择列表
快速实现Android多级树形列表,这个库是在鸿洋多级树形列表demo中修改而来. 解决的问题: 1. 支持ID为int类型和String类型. 2. 支持多级复选框选中,使用只需一行代码. 3. 支 ...