Find the winner of the Game to Win by erasing any two consecutive similar alphabets - GeeksforGeeks

02 Jun, 2021
Given a string consisting of lower case alphabets.Rules of the Game:  
A player can choose a pair of similar consecutive characters and erase them.
There are two players playing the game, the player who makes the last move wins.
The task is to find the winner if A goes first and both play optimally. Examples:  
Input: str = "kaak" 
Output: B
Explanation:
    Initial String: "kaak"
    A's turn:
        removes: "aa"
        Remaining String: "kk"
    B's turn:
        removes: "kk"
        Remaining String: ""
    Since B was the last one to play
    B is the winner.

Input: str = "kk"
Output: A
 
Approach: We can use a stack to simplify the problem.  
Each time we encounter a character that is different from the one present in the top of the stack we add it to the stack.
If the stack top and the next character match we pop the character from the stack and increment the count.
At the end, we just need to see who wins by checking count%2.
Below is the implementation of the above approach:  
C++
Java
Python3
C#
Javascript
#include <bits/stdc++.h>using namespace std; // Function to play the game// and find the winnervoid findWinner(string s){    int i, count = 0, n;    n = s.length();    stack<char> st;     // ckecking the top of the stack with    // the i th character of the string    // add it to the stack if they are different    // otherwise increment count    for (i = 0; i < n; i++) {        if (st.empty() || st.top() != s[i]) {            st.push(s[i]);        }        else {            count++;            st.pop();        }    }     // Check who has won    if (count % 2 == 0) {        cout << "B" << endl;    }    else {        cout << "A" << endl;    }} // Driver codeint main(){    string s = "kaak";     findWinner(s);     return 0;}
// Java implementation for above approachimport java.util.*; class GFG{ // Function to play the game// and find the winnerstatic void findWinner(String s){    int i, count = 0, n;    n = s.length();    Stack<Character> st = new Stack<Character>();     // ckecking the top of the stack with    // the i th character of the string    // add it to the stack if they are different    // otherwise increment count    for (i = 0; i < n; i++)    {        if (st.isEmpty() ||            st.peek() != s.charAt(i))        {            st.push(s.charAt(i));        }        else        {            count++;            st.pop();        }    }     // Check who has won    if (count % 2 == 0)    {        System.out.println("B");    }    else    {        System.out.println("A");    }} // Driver codepublic static void main(String[] args){    String s = "kaak";     findWinner(s);}} // This code is contributed by Rajput-Ji
# Python3 implementation of the approach # Function to play the game# and find the winnerdef findWinner(s) :     count = 0    n = len(s);    st = [];     # ckecking the top of the stack with    # the i th character of the string    # add it to the stack if they are different    # otherwise increment count    for i in range(n) :        if (len(st) == 0 or st[-1] != s[i]) :            st.append(s[i]);                     else :            count += 1;            st.pop();     # Check who has won    if (count % 2 == 0) :        print("B");         else :        print("A");         # Driver codeif __name__ == "__main__" :     s = "kaak";     findWinner(s); # This code is contributed by AnkitRai01
// C# implementation for above approachusing System;using System.Collections.Generic; class GFG{ // Function to play the game// and find the winnerstatic void findWinner(String s){    int i, count = 0, n;    n = s.Length;    Stack<char> st = new Stack<char>();     // ckecking the top of the stack with    // the i th character of the string    // add it to the stack if they are different    // otherwise increment count    for (i = 0; i < n; i++)    {        if (st.Count == 0 ||            st.Peek() != s[i])        {            st.Push(s[i]);        }        else        {            count++;            st.Pop();        }    }     // Check who has won    if (count % 2 == 0)    {        Console.WriteLine("B");    }    else    {        Console.WriteLine("A");    }} // Driver codepublic static void Main(String[] args){    String s = "kaak";     findWinner(s);}} // This code is contributed by 29AjayKumar
<script>    // Javascript implementation for above approach         // Function to play the game    // and find the winner    function findWinner(s)    {        let i, count = 0, n;        n = s.length;        let st = [];         // ckecking the top of the stack with        // the i th character of the string        // add it to the stack if they are different        // otherwise increment count        for (i = 0; i < n; i++)        {            if (st.length == 0 ||                st[st.length - 1] != s[i])            {                st.push(s[i]);            }            else            {                count++;                st.pop();            }        }         // Check who has won        if (count % 2 == 0)        {            document.write("B");        }        else        {            document.write("A");        }    }         let s = "kaak";       findWinner(s); // This code is contributed by divyesh072019.</script>
B
 
Rajput-Ji
ankthon
29AjayKumar
tr23
divyesh072019
cpp-stack-functions
Game Theory
Stack
Stack
Game Theory
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Expectimax Algorithm in Game Theory
Find the winner in nim-game
Game Theory (Normal-form Game) | Set 4 (Dominance Property-Pure Strategy)
Find the player who will win by choosing a number in range [1, K] with sum total N
Game Theory (Normal-form game) | Set 3 (Game with Mixed Strategy)
Stack Data Structure (Introduction and Program)
Stack Class in Java
Stack in Python
Check for Balanced Brackets in an expression (well-formedness) using Stack
Program for Tower of Hanoi