vj266A--Stones on the Table

问题来源

vj266A

问题描述

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.

输入

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.

输出

Print a single integer — the answer to the problem.

例子

vj266A--Stones on the Table

AC的代码

#include <iostream>
using namespace std;
int main()
{
	     int i,k=0,max=0,sum=0;
		 char t[50];
		 cin >> i;
		 cin >> t;
		for (int j = 0; j < (i-1); j++)
		{
			if (t[j] == t[(j + 1)])
			{
				k++;
				if(j!=(i-2))
				continue;
			}
			sum = sum + k;
		    k = 0;
		}
	cout << sum;

}

解题思路

输入i作为示例数,用字符数组t保存字符。for循环检查这一位和高一位的字符是否相同,如果相同,则要除去一个字母,用k计数,如果不相同,用sum记录前面应除的字母数,再将k置0,再继续判断,直到字符串结束。输出sum。