题解 | #牛群的配对# 提供一个不太屎的方案

牛群的配对

https://www.nowcoder.com/practice/c6677c8bd0d946e191051f19100c5cf5

class Solution {
  public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param s string字符串
     * @return bool布尔型
     */
    bool isValidPairing(string s) {
        stack<char> stk;
        int index = 0;
        char tmps, tmpt;
        if(s.length() % 2 == 1) return false;

        while(index < s.length()){
            if(stk.empty()){
                stk.push(s.at(index));
            }
            else{
                tmps = s.at(index);
                tmpt = stk.top();
                if(tmps == 'B' && tmpt == 'A') stk.pop();
                else if(tmps == 'D' && tmpt == 'C') stk.pop();
                else stk.push(tmps);
            }
            index++;
        }

        return stk.empty();
    }






};

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务