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



时间: 2024-09-08 09:21:57

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

[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 "([)]

LeetCode 20 Valid Parentheses(有效的括号)

翻译 给定一个只包含'(', ')', '{', '}', '[' 和']'的字符串,判断这个输入的字符串是否是有效的. 括号必须在正确的形式下闭合,"()" 和"()[]{}" 是有效的,但是 "(]" 和"([)]" 则不是. 原文 Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the

LeetCode 32 Longest Valid Parentheses(最长有效括号)(*)

翻译 给定一个仅仅包含"("或")"的字符串,找到其中最长有效括号子集的长度. 对于"(()",它的最长有效括号子集是"()",长度为2. 另一个例子")()())",它的最长有效括号子集是"()()",其长度是4. 原文 Given a string containing just the characters '(' and ')', find the length of the l

[LeetCode]32.Longest Valid Parentheses

题目 Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring. For "(()", the longest valid parentheses substring is "()", which has length = 2. Another example i

leetcode 22 Generate Parentheses关于C++ string的问题

问题描述 leetcode 22 Generate Parentheses关于C++ string的问题 /* Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. For example, given n = 3, a solution set is: "((()))", "(()())", "(())

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 "([)]"

Longest Valid Parentheses

Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring. For "(()", the longest valid parentheses substring is "()", which has length = 2. Another example is &

代码-C/C++ 用顺序表实现的括号匹配问题

问题描述 C/C++ 用顺序表实现的括号匹配问题 我的代码 #include<stdio.h> #include<string.h> #define TRUE 1 #define FALSE 0 typedef struct { char data[100]; int top; }Stack; int InitStack(Stack stack) { stack.top=-1; return TRUE; } int Push(Stack &stackchar &ch

九度题目1153:括号匹配问题

题目1153:括号匹配问题 时间限制:1 秒 内存限制:32 兆 特殊判题:否 提交:2965 解决:1315 题目描述:     在某个字符串(长度不超过100)中有左括号.右括号和大小写字母:规定(与常见的算数式子一样)任何一个左括号都从内到外与在它右 边且距离最近的右括号匹配.写一个程序,找到无法匹配的左括号和右括号,输出原来字符串,并在下一行标出不能匹配的括号.不能匹配的 左括号用"$"标注,不能匹配的右括号用"?"标注. 输入:     输入包括多组数据,