Sherlock and the Valid String

  • + 0 comments
    string isValid(string s) {
        bool valid = true;
        map<char,int> ocurrence;
        for(int i = 0;i<s.size();i++) ocurrence[s[i]]++;
        map<int,int> repeatence;
        map<char,int>::iterator itr;
        for(itr = ocurrence.begin();itr!=ocurrence.end();++itr)
            repeatence[itr->second]++;
        
        /* debug
        cout << "repeatence: " << repeatence.size()<< endl;
        for(auto i:repeatence)
            cout << " " << i.first << " " << i.second << endl;
        
        */
        
        
        if(repeatence.size()>2) valid = false;
        if(repeatence.size()==2) {
            
            /* debug
            
            
            map<int,int>:: iterator it;
            it = repeatence.begin();
            cout << "repeatence.begin()->first: " << it->first << endl;
            ++it;
            cout << "repeatence.end()->first: " << it->first << endl;
            
            cout << "abs(repeatence.begin()->first - repeatence.end()->first): "
                << abs(repeatence.begin()->first - repeatence.end()->first) << endl;
                
            
            */
            
            map<int,int>:: iterator it;
            it = repeatence.begin();
            int diff = it->first;
            int val[2];
            val[0] = it->second;
            if(diff == 1 and val[0] == 1) goto xx;
            ++it;
            diff -= it->first;
            val[1] = it->second;
            diff=abs(diff) - 1;
            if(diff) valid = false;
            
            //cout << valid << endl;
            
            if(!(val[0] == 1 || val[1] == 1))
                valid = false;
                
        } 
        xx:
        
        return valid?"YES":"NO";
    }