有效的括号(Python and C++解法)

题目:

给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。

有效字符串需满足:

左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。

示例 1:

输入: "()[]{}"  输出: true

示例2 :

输入: "(]"  输出: false

示例 3:

输入: "([)]"  输出: false

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/valid-parentheses

思路:

  如果遍历到左括号就入栈;如果遍历到右括号就与栈顶括号比较,如果匹配就返回真,不匹配或者栈为空就返回假。

Python解法:

 1 class Solution(object):
 2     @staticmethod
 3     def is_valid(s: str) -> bool:
 4         if s is None:
 5             return True
 6         stack = []  # 存储左括号
 7         brackets_map = {')':'(', ']':'[', '}':'{'}  # 创建字典(key:value),右括号作为key,用于查找
 8         for c in s:
 9             if c not in brackets_map:
10                 stack.append(c)  # 遇到左括号就需要入栈
11             # 如果遇到右括号后,栈中没有元素,或者当前右括号的value不等于栈顶元素
12             elif stack == [] or brackets_map[c] is not stack.pop():  # 不能使用stack is None,可以使用not stack
13                     return False
14         return not stack  # 如果遍历结束后,栈为空才返回True

C++解法:

 1 #include "pch.h"
 2 #include <iostream>
 3 #include <stack>
 4 #include <string>
 5 #include <unordered_map>
 6 using namespace std;
 7 
 8 class Solution {
 9 public:
10     bool isValid(string s) {
11         if (s.length() == 0)   return true;
12         stack<char> storeRight;  // 存储左括号的栈
13         // 创建字典(key:value),右括号作为key,用于查找
14         unordered_map<char, char> brackets{
15             {')','('},
16             {']','['},
17             {'}','{'} };
18         for (int i = 0; i < s.length(); i++) {
19             if (!(brackets.find(s[i]) != brackets.end())) {  // 遇到左括号
20                 storeRight.push(s[i]);  // 左括号需要入栈
21                 continue;
22             }
23             // 如果遇到右括号后,栈中没有元素,或者当前右括号的value不等于栈顶元素
24             else if (storeRight.empty() || brackets[s[i]] != storeRight.top())
25                 return false;
26             storeRight.pop();  // 匹配成功就弹出
27         }
28         return storeRight.empty();
29     }
30 };
31 
32 int main() {
33     Solution s;
34     string theS = "()[]{}";
35     cout << s.isValid(theS);
36 }
原文地址:https://www.cnblogs.com/kongzimengzixiaozhuzi/p/12995064.html