【LeetCode 20】关关的刷题日记45 – Valid Parenthese

时间:2022-05-07
本文章向大家介绍【LeetCode 20】关关的刷题日记45 – Valid Parenthese,主要内容包括题目、思路、基本概念、基础应用、原理机制和需要注意的事项等,并结合实例形式分析了其使用技巧,希望通过本文能帮助到大家理解应用这部分内容。

关关的刷题日记45 – Leetcode 20. Valid Parenthese

题目

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.

题目的意思是判断给定的字符串中的各个括号字符的出现是否符合括号构成的规则。

思路

思路:只要遇到括号匹配的问题,我们就选择用栈,遇到左括号就进栈,遇到右括号,就判断栈顶元素是否与之匹配,匹配的话就pop出栈,不匹配的话就返回false。用到了栈的一些语法:栈如果是空的,取栈顶元素会越界,必须得保证栈不是空的前提下,才能取栈顶元素。

class Solution {
public:
    bool isValid(string s) {
        stack<char>store;
        for(int i=0; i<s.size(); i++)
        {
            if(s[i]=='(' || s[i]=='{' || s[i]=='[')
                store.push(s[i]);
            else
            {
                if(store.empty())
                    return false;
                else
                {
                    int temp=store.top();
                    if( s[i]==')' && temp=='(' || s[i]==']' && temp=='[' || s[i]=='}' && temp=='{')
                        store.pop();
                    else
                        return false;
                }        
            }
        }
        if(store.empty())
            return true;
        else
            return false;
    }
};

人生易老,唯有陪伴最长情,加油!

以上就是关关关于这道题的总结经验,希望大家能够理解,有什么问题可以在我们的专知公众号平台上交流或者加我们的QQ专知-人工智能交流群 426491390,也可以加入专知——Leetcode刷题交流群(请先加微信小助手weixinhao: Rancho_Fang)。