c_cpp HR-SherlockAndTheValidString

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp HR-SherlockAndTheValidString相关的知识,希望对你有一定的参考价值。

#include <bits/stdc++.h>

using namespace std;

// Complete the isValid function below.
string isValid(string s) {
    map<char,int> count;
    for(int i=0;i<s.size();i++){
        count[s[i]]++; // freq of alphabets
    }
    map<int,int> countFreq;
    for(auto i=count.begin();i!=count.end();i++){
        countFreq[i->second]++; // freq of frequencies
    }
    if(countFreq.size()==1){
        return "YES"; // all have same frequency
    }
    if(countFreq.size()>2){
        return "NO"; // not possible to delete more than 1 element
    }
    vector<pair<int,int> >a;
    for(auto i=countFreq.begin();i!=countFreq.end();i++){
        a.push_back({i->first,i->second});
    }
    if(a[0].second==1 && a[1].second==1){
        if(abs(a[0].first-a[1].first)>1){
            return "NO";
        }else{
            return "YES";
        }
    }
    if(a[1].second<a[0].second){
        pair<int,int> temp;
        temp=a[0];
        a[0]=a[1];
        a[1]=temp;
    }
    if(a[0].second>1){ // there should be only one element with diff freq
        return "NO";
    }
    if(a[0].first-a[1].first==1 || a[0].first==1){ // element to be deleted must have single difference
        //with maxfreq elements
        return "YES";
    }
    return "NO";
}

int main()
{
    ofstream fout(getenv("OUTPUT_PATH"));

    string s;
    getline(cin, s);

    string result = isValid(s);

    fout << result << "\n";

    fout.close();

    return 0;
}

以上是关于c_cpp HR-SherlockAndTheValidString的主要内容,如果未能解决你的问题,请参考以下文章

c_cpp 127.单词阶梯

c_cpp MOFSET

c_cpp MOFSET

c_cpp 31.下一个排列

c_cpp string→char *

c_cpp 54.螺旋矩阵