美文网首页
20.有效的括号

20.有效的括号

作者: su945 | 来源:发表于2020-06-22 22:52 被阅读0次

题目描述

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

有效字符串需满足:

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

问题分析

利用栈的特性进行判断括号是否是成对进行出现的

解题思路1

#include <vector>
#include <string>
#include <stack>
using namespace std;

class Solution
{
public:
    bool isValid(string s)
    {
        stack<char> store;
        auto strSize = s.size();
        if(strSize % 2 == 1){
            return false;
        }
        for (auto tmpChar : s)
        {
            char popChar = ' ';
            switch (tmpChar)
            {
            //如果是(,[,{,就压入栈中
            case '(':
            case '[':
            case '{':
                store.push(tmpChar);
                break;
            case ')':
                //注意栈为空的情况
                if (store.empty())
                {
                    return false;
                }
                popChar = store.top();
                store.pop();
                if (popChar != '(')
                {
                    return false;
                }
                break;
            case ']':
                if (store.empty())
                {
                    return false;
                }
                popChar = store.top();
                store.pop();
                if (popChar != '[')
                {
                    return false;
                }
                break;
            case '}':
                if (store.empty())
                {
                    return false;
                }
                popChar = store.top();
                store.pop();
                if (popChar != '{')
                {
                    return false;
                }
                break;
            default:
                return false;
                break;
            }
        }
        if (store.empty())
        {
            return true;
        }
        else
        {
            return false;
        }
    }
};

相关文章

网友评论

      本文标题:20.有效的括号

      本文链接:https://www.haomeiwen.com/subject/uflqfktx.html