實現刪除字符串中出現次數最少的字符

實現刪除字符串中出現次數最少的字符,若多個字符出現次數一樣,則都刪除。輸出刪除這些單詞後的字符串,字符串中其它字符保持原來的順序。
字符串只包含小寫英文字母, 不考慮非法輸入,輸入的字符串長度小於等於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;
}
發佈了106 篇原創文章 · 獲贊 18 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章