给定一排银币,其中有一个特殊的金币。两名玩家玩游戏,每走一步,玩家必须从行的左端或右端取出一枚硬币,取出特殊硬币的玩家赢得游戏。任务是找到游戏的赢家。
例子:
Input: str = “GSSS”
Output: First
The first player directly removes the special gold coin.
Input: str = “SGS”
Output: Second
Irrespective of which coin the first player removes, the special
gold coin becomes exposed and is removed by the second player.
方法:举几个例子可以看出,如果银币的数量是奇数,则第一个玩家获胜,否则第二个玩家获胜。特殊情况下,金币在角落时,无论银币多少,先到者为赢家。
下面是上述方法的实现:
C++
// C++ implementation of the approach
#include
using namespace std;
// Function to return the
// winner of the game
string getWinner(string str, int len)
{
// To store the count of silver coins
int total = 0;
if(str[0]=='G' ||str[len-1]=='G')
return "First";
else{
for (int i = 0; i < len; i++) {
// Update the position of
// the gold coin
if (str[i] == 'S') {
total++;
}
}
// First player will win the game
if ((total % 2) == 1)
return "First";
return "Second";
}
}
// Driver code
int main()
{
string str = "GSSS";
int len = str.length();
cout << getWinner(str, len);
return 0;
}
Java
// Java implementation of the approach
import java.util.*;
class GFG
{
// Function to return the
// winner of the game
static String getWinner(String str, int len)
{
// To store the count of silver coins
int total = 0;
for (int i = 0; i < len; i++)
{
// Update the position of
// the gold coin
if (str.charAt(i) == 'S')
{
total++;
}
}
// First player will win the game
if ((total % 2) == 1)
return "First";
return "Second";
}
// Driver code
public static void main(String []args)
{
String str = "GSSS";
int len = str.length();
System.out.println(getWinner(str, len));
}
}
// This code is contributed by Surendra_Gangwar
Python3
# Python3 implementation of the approach
# Function to return the
# winner of the game
def getWinner(string, length) :
# To store the count of silver coins
total = 0;
for i in range(length) :
# Update the position of
# the gold coin
if (string[i] == 'S') :
total += 1;
# First player will win the game
if ((total % 2) == 1) :
return "First";
return "Second";
# Driver code
if __name__ == "__main__" :
string = "GSSS";
length = len(string);
print(getWinner(string, length));
# This code is contributed by kanugargng
C#
// C# implementation of the approach
using System;
class GFG
{
// Function to return the
// winner of the game
static String getWinner(String str, int len)
{
// To store the count of silver coins
int total = 0;
for (int i = 0; i < len; i++)
{
// Update the position of
// the gold coin
if (str[i] == 'S')
{
total++;
}
}
// First player will win the game
if ((total % 2) == 1)
return "First";
return "Second";
}
// Driver code
public static void Main(string []args)
{
string str = "GSSS";
int len = str.Length;
Console.WriteLine(getWinner(str, len));
}
}
// This code is contributed by rrrtnx.
Javascript
输出:
First
如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程和学生竞争性编程现场课程。