Valid Parentheses

来源:互联网 发布:涤纶低弹网络丝应香莲 编辑:程序博客网 时间:2024/06/08 17:38

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.

思路:使用堆栈

判断栈顶是否与字符串当前字符为左右匹配关系,若是,栈顶弹出,不是,将当前字符入栈。

边界检查:

1:空字符串 直接返回true;


class Solution {

public:
    bool isValid(string s) {
        int len = s.size();
        if(len == 0)return true;
        stack<char> st;
        int index = 0;
        while(index < len)
        {
            if(st.empty())
            {
                st.push(s[index]);
                index++;
                continue;
            }
            char c1 = st.top();
            char c2 = s[index];
            if((c1 == '(' && c2 == ')')||(c1 == '{' && c2 == '}')||(c1 == '[' && c2 == ']'))
            {
                st.pop();
            }
            else
            {
                st.push(c2);
            }
            index++;
        }
        if(st.empty())return true;
        else return false;
        
    }
};
0 0