CodeForces-266A Stones on the Table(语法练习题)

探讨一种算法,用于解决石头桌游戏中的问题:如何通过移除最少数量的石头,使桌上每颗相邻的石头颜色不同。输入为一串由BRG组成的字符串,代表蓝色、红色、绿色石头,算法需确定并返回需移除的石头数量。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Stones on the Table

time limit per test2 seconds
memory limit per test256 megabytes
inputstandard input
outputstandard output
There are n stones on the table in a row, each of them can be red, green or blue. Count the minimum number of stones to take from the table so that any two neighboring stones had different colors. Stones in a row are considered neighboring if there are no other stones between them.

Input
The first line contains integer n (1 ≤ n ≤ 50) — the number of stones on the table.

The next line contains string s, which represents the colors of the stones. We’ll consider the stones in the row numbered from 1 to n from left to right. Then the i-th character s equals “R”, if the i-th stone is red, “G”, if it’s green and “B”, if it’s blue.

Output
Print a single integer — the answer to the problem.

Examples
inputCopy
3
RRG
outputCopy
1
inputCopy
5
RRRRR
outputCopy
4
inputCopy
4
BRBG
outputCopy
0

问题简述:

  给出一个字符串,由"B",“R”,"G"组成,分别代表蓝色石头,红色石头,绿色石头,从中去掉几块石头才能使得相邻石头颜色不一样?

问题分析:

  对字符串做处理,将相邻的相同字符只保留一个,统计去掉的字符数。

程序说明:

  从头开始遍历字符串,若当前字符与下一个相同,去掉下一个,统计去掉的数量。

程序实现:

#include<iostream>
#include<string>
using namespace std;

int main()
{
    int n,sum=0;
    string str;
    cin>>n>>str;
    for(int i=0;i<str.size()-1;i++)
    {
        if(str[i]==str[i+1])
        {
            str.erase(i+1,1);
            i--;
            sum++;
        }
    }
    cout<<sum;
}
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值