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

牛群的配对

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

class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param s string字符串 
     * @return bool布尔型
     */
    
    bool isPair(const string& s, int indexL, int indexR){
        char nextChar = s.at(indexR);
        switch(s.at(indexL)){
            case 'A':
                if(nextChar == 'B') return true;
                else return false;
            case 'B':
                return false;
            case 'C':
                if(nextChar == 'D') return true;
                else return false;
            case 'D':
                return false;
            default:
                std::cout << "Invalid bull code..." << std::endl;
                return false;
        }
    }

    bool isValidPairing(string s) {
        bool tempFlag = false;
        string tempS = s;
        if(tempS.length()%2==1) return false;
        int indexL, indexR;
        while(tempS.length() > 1){
            indexL = 0;
            indexR = indexL + 1;
            while(!tempFlag && indexL < tempS.length() - 1){
                //cout << tempS.at(indexL) << " " << tempS.at(indexR) << endl;
                tempFlag = isPair(tempS, indexL, indexR);
                //cout << "tempFlag: " << tempFlag << endl;
                indexL += 1;
                indexR += 1;
            }
            if(indexL >= tempS.length() - 1 && !tempFlag) return false;
            if(indexL != 0){
                tempS = tempS.substr(0, indexL - 1) + tempS.substr(indexL + 1);
            }else{
                tempS = tempS.substr(indexL+1);
            }
            indexL = 0;
            indexR = 1;
            tempFlag = false;
        }
        return true;
    }






};

全部评论

相关推荐

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