题解 | 参议院投票

参议院投票

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

似乎并不需要计数器的,但我感觉带上计数器更容易理解一点

核心思想:双序列分别储存红黑帮的序列,然后靠前的人先弹劾,谁先把对面全弹了谁先赢;

class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 求出最终获胜帮派的名称
     * @param s string字符串 
     * @return string字符串
     */
    string predictVictory(string s) {
        // write code here

        int n = s.size();
        //储存各帮派的索引
        queue<int> Rperson; 
        queue<int> Dperson;
        int red_count = 0; //红帮计数器
        int dark_count = 0;//黑帮计数器
        for (int i = 1;i <= n; i++)
        {
            if (s[i-1] == 'R')
            {
                Rperson.push(i);
                red_count++;
            }
            else
            {
                Dperson.push(i);
                dark_count++;
            }
        }

        //开始投票
        while (!Rperson.empty() && !Dperson.empty())
        {
            int Rperson_idx = Rperson.front();//红帮当前位置
            int Dperson_idx = Dperson.front();//黑帮当前位置
            if(Rperson_idx < Dperson_idx)//红帮先手
            {
                Dperson.pop();//黑帮首位遗憾离场
                Rperson.pop();
                Rperson.push(Rperson_idx + n);
                dark_count--; //黑帮out一位
            }
            else //黑帮先手
            {
                Rperson.pop();//红帮首位遗憾离场
                Dperson.pop();
                Dperson.push(Dperson_idx + n);
                red_count--; //红帮out一位
            }
        }
        if (red_count == 0) //红帮全员离场
        {
            return "Dark"; //黑帮当选
        }
        else //黑帮全员out
        {
            return "Red"; //红帮胜利
        }
    }
};

全部评论

相关推荐

点赞 评论 收藏
分享
03-02 08:18
集美大学 Java
钱嘛数字而已:没有赛事奖项么?另外,项目经历字有点多哈,建议突出一下重点:用的什么技术,解决什么问题,达到什么效果。
大家都开始春招面试了吗
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务