20 有效的括号

编译技术学过

class Solution {
public:
    bool isValid(string s) {

        stack<char> sts;

        if( s.size() % 2 != 0)
            return false;

        for(int i = 0; i < s.size(); i++)
        {
            if( s[i] == '(' ) 
                sts.push (')');

            else if ( s[i] == '[' ) 
                sts.push (']');

            else if ( s[i] == '{' ) 
                sts.push ('}');

            else if ( sts.empty() || s[i] != sts.top() )
                return false;

            else sts.pop();
        }
		//这里不能直接返回true,如果栈不为空,但是遍历完了s,是左边的括号多了
        return sts.empty();
    }
};
posted @ 2025-03-03 20:35  名字好难想zzz  阅读(7)  评论(0)    收藏  举报