Codeforces 266A Stones on the Table Solution & Explanation

Difficulty : 800

Problem Description

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

Input3
RRG
Output1
Input5
RRRRR
Output4
Input4
BRBG
Output0

Solution

The only thing to be aware of is the example 2, where ‘RRRRR‘ will return an answer of 4. This means that even if all the stones have the same color, you still need to count them all. (We need to take 5-1 stones to make them without same color in neighboring stones).

C# Solution

Solution1

int n = int.Parse(Console.ReadLine());
string text = Console.ReadLine();

char[] charArr = text.ToCharArray();
char now = charArr[0];
int cnt = 0;

for(int i=1; i<charArr.Length;i++)
{
    if(charArr[i]!=now){
        now = charArr[i];
    }
    else {
        cnt+=1;        
    }
}

Console.WriteLine(cnt);

Java Solution

Solution1

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        scanner.nextLine();

        char[] charArr = scanner.nextLine().toCharArray();
        char now = charArr[0];
        int cnt = 0;

        for(int i=1;i<charArr.length;i++){
            if(charArr[i]!=now){
                now = charArr[i];
            }
            else {
                cnt+=1;        
            }
        }

        System.out.println(cnt);
    }
}

Python3 Solution

Solution1

n = input()
inStr = input()

now = inStr[0]
cnt = 0

for i in range(1,len(inStr)):
    char = inStr[i]
    if(char!=now):
        now = char
    else :
        cnt+=1
        
print(cnt)

JavaScript Solution

Solution1

var n = readline();
var inStr = readline();

var now = inStr[0];
var cnt = 0;

for(var i=1; i<inStr.length; i++) {
    var char = inStr[i];
    if(char!==now){
        now = char;
    }
    else {
        cnt+=1;        
    }
}

print(cnt);

Conclusion

🧡If my solution helps, that is my honor!

🧡You can support me by sharing my posts, thanks you~~

✅If you got any problem about the explanation or you need other programming language solution, please feel free to let me know !!

The problem link : Problem – 266A – Codeforces

Random Codeforces Posts

Leave a Reply

Your email address will not be published. Required fields are marked *