88.删除字符串中字符最少字符
删除字符串中出现次数最少的字符,如果有多个字符出现次数一样,则都删除.
输入描述:输入abcdd 字符串中只包含小写英文字母。输出描述:dd
示例1 输入输出示例仅供调试,后台判题数据一般不包含示例
输入:abcdd 输出:dd
示例2:输入:aabbccdd,输出:empty,说明:如果字符串的字符都被删除,则范围empty
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/**
* 首先定义长度为26的数组count,用于记录每个小写字母出现的频率,
* 然后遍历字符串统计每个字符串出现的频率,然后找到频率最小的字符删除,最后在遍历输出
* @return
*/
//计算每个字符出现的次数
//找到最小的频率-删除-输出
void deleteMinChars(char*str){
int count[26]={0}; //记录频率
int minCount= strlen(str);
for (int i = 0; i < strlen(str) ; ++i) {
count[str[i]-'a']++;
}
for (int i = 0; i <26 ; ++i) {//栈道最小频率字符
if(count[i]>0&&count[i]<minCount){
minCount=count[i];
}
}
int i=0;
while (str[i]!='\0'){
if(count[str[i]-'a']==minCount){
int j=i;
//这里使用两个while循环,实现字符串的移动,
// 外层循环遍历字符串的每个字符,内层循环将当前字符之后的字符串逐渐前移,来删除最小频率的字符
while (str[j]!='\0'){
str[j]=str[j+1];
j++;
}
} else{
i++;
}
}
if(strlen(str)==0){
printf("empty");
}else{
printf("%s",str);
}
}
int main(){
setbuf(stdout, NULL);
char str[100];
printf("请输入字符串:\n");
scanf("%s",str);
deleteMinChars(str);
return 0;
}
首先定义一个长度为26的数组count,用于记录每个小写英文字母的出现频率。然后,遍历字符串,统计每个字符的出现频率。接着,找到出现频率最小的字符的频率值minCount。最后,再次遍历字符串,删除出现频率为minCount的字符,并输出结果。
C语言:力扣88题,删除字符串中字符最少字符
最新推荐文章于 2024-04-25 12:15:22 发布