zoukankan      html  css  js  c++  java
  • [leetcode]Valid Parentheses

    简单题。使用stack就行了。不过一开始忘了判断'['和']'的情况。要判断stack是否为空。

    #include <string>
    #include <stack>
    
    using namespace std;
    
    class Solution {
    public:
        bool isValid(string s) {
            // Start typing your C/C++ solution below
            // DO NOT write int main() function
            stack<char> st;
        	for (int i = 0; i < s.size(); i++)
    		{
    			if (s[i] == '(' || s[i] == '[' || s[i] == '{')
    			{
    				st.push(s[i]);
    			}
    			else if (s[i] == ')' || s[i] == ']' || s[i] == '}')
    			{
                    if (st.empty()) return false;
    				char c = st.top();
    				st.pop();
    				if (c == '(' && s[i] != ')') return false;
    				if (c == '[' && s[i] != ']') return false;
    				if (c == '{' && s[i] != '}') return false;
    			}
    		}
            if (!st.empty()) return false;
    		return true;
        }
    };
    

    python3

    class Solution:
        def isValid(self, s: str) -> bool:
            stack = []
            mapping = {'(': ')', '{': '}', '[': ']'}
            for c in s:
                if len(stack) == 0:
                    stack.append(c)
                else:
                    p = stack.pop()
                    if p in mapping and c == mapping[p]:
                        continue
                    else:
                        stack.append(p)
                        stack.append(c)
            return len(stack) == 0
    

      

  • 相关阅读:
    LeetCode 225. 用队列实现栈 做题笔记
    杨辉三角
    字母图形
    01字符串
    圆的面积
    饮料和啤酒
    进制转换
    从今天起 复习算法
    乘法群
    Paillier同态加密的介绍以及c++实现
  • 原文地址:https://www.cnblogs.com/lautsie/p/3224026.html
Copyright © 2011-2022 走看看