LeetCode 【20.有效的括号】

在这里插入图片描述

class Solution 
{
    
    
public:
    bool isMatch(char left,char right)//定义辅助函数是否匹配
    {
    
    
        switch(right)
        {
    
    
        case ')':
        return left=='(';
        case ']':
        return left=='[';
        case '}':
        return left=='{';
        default:
        return false;
        }
    }
    bool isValid(string s) 
    {
    
    
     stack<char>validateStack;
     if(s.length()==0)//空字符串返回真
     {
    
    
         return true;
     }
     for(auto currentChar:s)
     {
    
    
         if(currentChar==')'||currentChar==']'||currentChar=='}')
         {
    
    
         if(validateStack.empty()||!isMatch(validateStack.top(),currentChar))//右括号判断是否匹配
         {
    
    
             return false;
         }
         else
         {
    
    
             validateStack.pop();
         }
     }
     else
     {
    
    
         validateStack.push(currentChar);//左括号入栈等待匹配
     }
     }
     return validateStack.empty();//完全匹配的要求是栈为空
    }
};

猜你喜欢

转载自blog.csdn.net/qq_45657288/article/details/112377355