LeetCode 20-Valid Parentheses(栈)

版权声明:转载请注明出处 https://blog.csdn.net/FGY_u/article/details/84348748

题目: https://leetcode.com/problems/valid-parentheses/

概述: 符号匹配问题,问是否所有的开符号都对应一个闭符号。

思路: 用个栈即可

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

猜你喜欢

转载自blog.csdn.net/FGY_u/article/details/84348748