NC52 括号序列

题目描述:

给出一个仅包含字符’(’,’)’,’{’,’}’,’[‘和’]’,的字符串,判断给出的字符串是否是合法的括号序列
括号必须以正确的顺序关闭,"()“和”()[]{}“都是合法的括号序列,但”(]“和”([)]"不合法。

解题分析:

使用栈模拟,遍历string:

  • 若栈为空,则将当前字符加入栈;
  • 若当前字符不能与栈中的首字符配对,则将当前字符加入栈;
  • 若当前字符能与栈中的首字符配对,则将栈中的首字符出栈;
  • 最后判断栈是否为空,为空的话则所有括号都是配对的,否则不是配对的。
class Solution {
    
    
public:
    /**
     * 
     * @param s string字符串 
     * @return bool布尔型
     */
    bool isValid(string s) {
    
    
        // write code here
        stack<char> charStack;
        for(auto c:s){
    
    
            if(charStack.empty()){
    
    
                charStack.push(c);
            }
            else{
    
    
                char temp=charStack.top();
                if((temp=='(' && c!=')') || (temp=='[' && c!=']') || (temp=='{' && c!='}'))
                    charStack.push(c);
                else
                    charStack.pop();
            }
        }
        return charStack.empty() ? true : false;
    }
};

猜你喜欢

转载自blog.csdn.net/MaopengLee/article/details/118873593