[ LeetCode ] #20. Valid Parentheses(符号匹配 C++ & Python)

题目:20. Valid Parentheses

Given a string containing just the characters '('')''{''}''[' and ']', determine if the input string is valid.

An input string is valid if:

  1. Open brackets must be closed by the same type of brackets.
  2. Open brackets must be closed in the correct order.

Note that an empty string is also considered valid.

Example 1:

Input: "()"
Output: true

Example 2:

Input: "()[]{}"
Output: true

Example 3:

Input: "(]"
Output: false

Example 4:

Input: "([)]"
Output: false

Example 5:

Input: "{[]}"
Output: true

题意:

符号匹配简化版,之所以称为简化版 是因为这里似乎不需要考虑优先级的问题。

分析:

既然不需要考虑优先级,那么 简单配对即可实现,这里首先使用python 中的list模拟实现栈的功能。如下

Code & Python

class Solution:
    def isValid(self, s: str) -> bool:
        a=[]
        count=0
        left = ['(','{','[']
        mapping = {')':'(',']':'[','}':'{'}
        for brackets in s:
            if brackets in left:
                a.append(brackets)
            else:
                if len(a)==0:return False
                if a.pop(-1) != mapping[brackets]:
                    return False
        if len(a)==0:
            return True
        return False

结果:

Runtime: 40 ms, faster than 47.54% of Python3 online submissions for Valid Parentheses.

Memory Usage: 13.3 MB, less than 5.22% of Python3 online submissions for Valid Parentheses.

Code & C++

class Solution {
public:
    bool isValid(string s) {
        	int len = s.size();
	if (len==0)return true;
	stack<char> tmp;
	string left="({[";
	map<char,char> mapping = {{')','('},{']','['},{'}','{'}};
	for(int i=0;i<len;++i){
		if(left.find(s[i])!=string::npos){
			tmp.push(s[i]);
		}else{
			char ch = mapping[s[i]];
			if(tmp.empty()){
				return false;
			}
			if(ch == tmp.top()){
				tmp.pop();
			}else{
				return false;
			}
		}
	}
	if(tmp.empty()) return true;
	return false;
    }
};

结果:

Runtime: 4 ms, faster than 100.00% of C++ online submissions for Valid Parentheses.

Memory Usage: 9.1 MB, less than 14.29% of C++ online submissions for Valid Parentheses.

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值