前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >leetcode 20 Valid Parentheses 括号匹配

leetcode 20 Valid Parentheses 括号匹配

作者头像
流川疯
发布2019-01-18 15:32:10
4680
发布2019-01-18 15:32:10
举报

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 的代码:

代码语言:javascript
复制
// 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;
}

另外一个看着好看点的:

代码语言:javascript
复制
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代码:

代码语言:javascript
复制
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 == []
代码语言:javascript
复制
</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
代码语言:javascript
复制
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
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2015年06月30日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档