Created
January 28, 2019 22:41
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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