牛客竞赛对一个字符串进行删除求删除最少多少个能让这个字符串变成一个完全回文串

一。题目:

Ramen likes palindrome.

A palindrome is a word, number, phrase, or other sequences of characters which reads the same backward as forward, such as madam or racecar or the number 10801.

An all palindrome is such a string that each substring of it is a palindrome. For example, the string aaa is an all palindrome while aba is not.

There is a string, and Ramen wants to make it an all palindrome string. He has a magic skill that he can remove any character of the string as much as he wants. But cast such a spell will cost him a lot of energy. As a lazy boy, he wants to save energy to play games, so can you tell him the minimum number of the necessary characters that he needs to remove?

输入描述:

The input contains precisely two lines.

The first line is an integer n(1 <= n <= 100000), which indicates the length of the given string.

The second line is the given string S. It’s guaranteed that S contains only lower case Lattin letters, i.e., a-z.

输出描述:

For each test case, output the minimum number of necessary removals.

示例1
输入

22
welcometotheupcofhitwh

输出

19

示例2
输入

20
itstheeasiestproblem

输出

16

示例3
输入

25
goandgrabyoursignupreward

输出

21

二.分析:

根据题意,要是完全回文子串,必须保证字符串中只有一种字符,要使字符串删除元素最少,则保留单个字符数量最多的那个字符,其他删除即可。故很显然该题就是一个求单个字符出现的最大次数问题。用普通for循环暴力求解会时间超限那么有没有好的方法来降低时间复杂度呢.?再次对题意进行分析,可以发现只有所有的小写字母,所以可以采用哈希的思想,用单个字符的ASCLL码为数组的下表去存储字符的个数。只需要一遍层for循环即可求解。最后找次数最多的字符,用总数减去即可。

三.解法:

1.C语言实现:

#include<stdio.h>
int main(){
	int a[130] = {0};
	int n,max=0,i;
	scanf("%d",&n);
	char hash[n];
	scanf("%s",&hash);
	for(i=0; i<n; i++){
		a[hash[i]]++;		
	}
	for(i=0; i<130;i++){
		if(max<a[i])
			max = a[i];
	}
	printf("%d",n-max);
 }

2.改进C语言实现:(降低空间复杂度,只需要26个存储空间即可存储每个字符出现的次数)

#include<stdio.h>
#include<string.h>
char s[100005];
int main()
{
     int n;
     long long cnt[26]={0};
     long long maxx=0;
     scanf("%d",&n);
     getchar();
     for(int i=1;i<=n;i++)
     {
         scanf("%c",&s[i]);
         cnt[s[i]-'a']++;
     }
     for(int i=0;i<26;i++)
     {
         if(maxx<cnt[i])
            maxx=cnt[i];
     }
     printf("%lld",n-maxx);
     return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值