您的位置:首页 > 其它

实现删除字符串中出现次数最少的字符

2017-03-29 19:58 453 查看
实现删除字符串中出现次数最少的字符,若多个字符出现次数一样,则都删除。输出删除这些单词后的字符串,字符串中其它字符保持原来的顺序。

字符串只包含小写英文字母, 不考虑非法输入,输入的字符串长度小于等于20个字节。

#include <iostream>
#include <cstring>
using namespace std;
const int MAXSIZE = 20;

int  DeleteMinCh(char *buffer)
{
char *temp = buffer;

int len = strlen(buffer);
int a[26] = {0};
bool flag = true;
while(*temp != '\0')
{
a[*temp - 'a']++;
temp++;
}
int count = 0;
for(int i = 0; i < 26; i++)
{
if(a[i] > 0)
{
count++;
}
}

if(count == 1)
{
cout << buffer << endl;
return 0;
}

for(int i = 1; i < 20; i++)
{
if(flag == false)
{
break;
}
for(int j = 0; j < len; j++)
{
if(a[buffer[j] - 'a'] == i)
{
buffer[j] = '-';
flag = false;
}
}
}

char str[len + 1];
int j = 0;
for(int i = 0; i < len; i++)
{
if(buffer[i] != '-')
{
str[j++] = buffer[i];
}
}
str[j] = '\0';
cout << str << endl;
return 0;
}

int main()
{
// char buffer[1024];
// cin >> buffer;

// DeleteMinCh(buffer);

int i, j;
char str[20] = {0};
char arr[20] = {0};
while(cin>>str)
{
int sum[260000] = {0};

bool flag = true;

int len = strlen(str);
for(i = 0; i < len; i++)
{
sum[str[i] - 'a']++;
}//计算所有字母出现的次数并相加

for(int i = 1; i < 20; i++)
{
if(!flag)
{
break;
}

for(int j = 0; j < len; j++)
{
if(sum[str[j] - 'a'] == i)
{
str[j] = '-';
flag = false;
}
}
}

j = 0;
for(i = 0; i< len; i++)
{
if(str[i] != '-')
{
arr[j] = str[i];
j++;
}
}

arr[j] = '\0';
cout<<arr<<endl;
}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐