Skip to content

Instantly share code, notes, and snippets.

@roxsula
Created January 28, 2019 22:41
Show Gist options
  • Save roxsula/7d17d8163388f5f9dfb5b499663b561f to your computer and use it in GitHub Desktop.
Save roxsula/7d17d8163388f5f9dfb5b499663b561f to your computer and use it in GitHub Desktop.
Sherlock considers a string to be valid if all characters of the string appear the same number of times. It is also valid if he can remove just character at index in the string, and the remaining characters will occur the same number of times. Given a string , determine if it is valid. If so, return YES, otherwise return NO.
string isValid(string s) {
std::map<char, int> freq;
vector<int> list;
vector<int> vals;
vector<int>::iterator list_unique;
if(s.length() == 1) return "YES";
else
{
for(int i = 0; i < s.length(); i++){
if(freq.find(s[i]) == freq.end()) freq[s[i]] = 1;
else freq[s[i]] += 1;
}
for(auto const& i: freq) list.insert(list.end(), i.second);
vals = list;
sort(list.begin(), list.end());
list_unique = std::unique(list.begin(), list.end());
list.resize(std::distance(list.begin(),list_unique));
if(list.size() == 1){
return "YES";
}
else if(std::count(vals.begin(), vals.end(), 1) > 1){
return "NO";
}
else if(list.size() == 2 and (std::find(list.begin(), list.end(), 1) != list.end() or abs(list[0] - list[1]) == 1)){
return "YES";
}
else return "NO";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment