牛客网_华为机试_023_删除字符串中出现次数最少的字符

63 篇文章 1 订阅
28 篇文章 0 订阅

题目描述

实现删除字符串中出现次数最少的字符,若多个字符出现次数一样,则都删除。输出删除这些单词后的字符串,字符串中其它字符保持原来的顺序。 

输入描述:

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

输出描述:

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

示例1

输入

abcdd

输出

dd

思路一:刚开的思维太江化(-1s),代码很复杂,想的太复杂了。我是这么想的:统计26个字母的次数,找到最小次数,把最小次数的字符加入vector,然后遍历原字符串,如果不是在vector中则输出,2ms。 这种思路不可取,作为反面教材警示后人

#include <iostream>
#include <string>
#include <vector>
using namespace std;
//返回记录次数最小的一个或者多个字符
vector<char> least(vector<int> record, int& count)
{
    vector<char> res;
    vector<int> temp (record);
    //排序
    sort(temp.begin(), temp.end());
    int i = 0;
    while(temp[i] == 0)    //排序后第一个不为0的记录即为最小值
       ++i;
    int min = temp[i];
    for(int j = 0; j < record.size(); ++j)
    {
        if(record[j] == min)
            res.push_back(j + 'a');
    }
    count = min;    //字符串出现最少的次数
    return res;
}
 
 
int main()
{
    string str = "";
    while(getline(cin, str)){
        //26个小写字母且无非法输入
        vector<int> record(26, 0);
        for(char c : str)
        {
           ++record[c-'a'];
        }
        int count = 0;
        vector<char> Del = least(record, count);
        int len = str.size() - count * Del.size();    //计算删除后的总字符串长度
        string resStr (len, ' ');
        int i = 0;
        for(int j = 0; j < str.size(); j++)
        {
            char c = str[j];
            //若该字符不属于被删除对象则复制到新字符串中
            if(find(Del.begin(), Del.end(), c) == Del.end())
            {
                resStr[i] = c;
                ++i;
            }
        }
        cout << resStr << endl;
    }
    return 0;
}


思路二:只要遍历字符串,统计字符次数,然后再遍历一遍,同时保存次数最小值,遍历完后得到最小值。然后再遍历,如果次数大于最小次数则输出。2ms

#include <iostream>
#include <string>

using namespace std;
int main()
{
    string str = "";
    while(getline(cin, str)){
        int len = str.size();
        //26个小写字母且无非法输入
        int record[26] = {0};
        //统计字符数
        for(char c : str)
           ++record[c-'a'];
        //求最小次数
        int min = record[str[0] - 'a'];    //不要遍历record找最小值,太复杂太复杂太复杂
        for(int i = 0; i < len; ++i)
        {
            if(record[str[i] - 'a'] <= min)    
                min = record[str[i] - 'a'];
        }
        //输出
        for(int i = 0; i < len; ++i)
        {
            if(record[str[i] - 'a'] > min)    //只要大于min就输出,不需要事先记录要删除那些字符,省事不少
                cout << str[i];
        }
        cout << endl;
    }
    return 0;
}


思想不要僵化

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值