C语言之Easy Comparison

欢迎进入我的C语言世界

题目

Problem Description

Given a string S, your task is to simulate the following operations. At first, you should sort it by lexicographic order and generate an order string S’. Then, you should compare S’ with S character by character. Finally, you should output the number of different characters between S’ and S.
For example, if the original string S is “ACMICPC”, when we sort this string we could get a new string S’ “ACCCIMP”. Then we compare these two strings, we could find out that only two characters ‘A’ whose index is 0 and ‘C’ whose index is 1 are the same (index from 0), so there are 5 different characters.

Input

The first line of the input contains an integer T (T <= 10), indicating the number of cases. Each case begins with a line containing one integer n (1 <= n <= 100), the length of the string S. The next line contains the string, consisting of characters ‘A’ to ‘Z’.

Output

For each test case, print a line containing the test case number (beginning with 1) and the number of different characters between the two strings as said above.

Sample Input

4
2
AC
6
ACCEPT
7
ACMICPC
10
FZUACMICPC

Sample Output

Case 1: 0
Case 2: 0
Case 3: 5
Case 4: 10

答案

下面展示 实现代码

#include <stdio.h>
#include <iostream>
#include <cstring>
#include <algorithm>
#define Max 107
int T,N;
char arr1[Max];
char arr2[Max];
using namespace std; 
int main()
{
    
    	
	while(scanf("%d",&T) != EOF)
	{
    
    
		for(int i = 0; i < T; i++)
		{
    
    
			scanf("%d",&N);
			memset(arr1,0,sizeof(arr1));
			memset(arr2,0,sizeof(arr2));
			for(int j = 0; j < N; j++)
			{
    
    
				cin >> arr1[j];
			}
			strcpy(arr2,arr1);
			sort(arr2,arr2+N);
			int num = 0;//记录有几个字母不同 
			for(int j = 0; j < N; j++)
			{
    
    
				if(arr1[j] != arr2[j])
				{
    
    
					num++;
				}				
			}
			cout << "Case " << i+1 << ": " << num << endl;
		}
	}
	return 0;
 } 

本题感悟

本块内容可能来自课本或其他网站,若涉及侵权问题,请联系我进行删除,谢谢大家啦~

思路:

这题用了两个字符串进行一一比对,计算有几个不相同的。

以上。

猜你喜欢

转载自blog.csdn.net/hongguoya/article/details/105837036
今日推荐