题解 | #删除字符串中出现次数最少的字符#

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

https://www.nowcoder.com/practice/05182d328eb848dda7fdd5e029a56da9

#include <iostream>
#include <string>

using namespace std;

int main() {
    string string1,string2;
    int small = 20;
    cin >> string1;
    int cnt[27] = {0};
    for(int i = 0;i<string1.size();i++)
    {
      cnt[stoi(to_string(string1[i])) - 97]++;
    }
    for(int i = 0; i< 27 ;i++)
        if(cnt[i]!=0 && cnt[i]<small)
            small = cnt[i];
    for(int i = 0;i<string1.size();i++)
    {
        if(cnt[(string1[i]-97)]!=small)
            string2+=string1[i];
    }
    cout<<string2;
}

建立一个数组,将a-z的出现次数依次对应输入,然后再查找其中最小的值,由于字符串最大长度为20,故small一开始设置为20,遇上非零且小于其的值,便等于该值,最后small便等于字符串中出现的最小次数,然后再将string1中的每一个字符放入string2,进行判断,如果该字符的出现次数不为最小值的话

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务