You are viewing a single comment's thread. Return to all comments →
My C++ solution:
string isValid(string s) { map<char,int> charmap; for (char c : s) { charmap[c]++; } map<int, int> freqCounts; for (auto const& pair : charmap) { freqCounts[pair.second]++; } if (freqCounts.size() == 1) { return "YES"; } if (freqCounts.size() == 2) { vector<pair<int, int>> freqs(freqCounts.begin(), freqCounts.end()); int freq1 = freqs[0].first; int count1 = freqs[0].second; int freq2 = freqs[1].first; int count2 = freqs[1].second; if ((freq1 == 1 && count1 == 1) || (freq2 == 1 && count2 == 1)) { return "YES"; } if ((abs(freq1 - freq2) == 1) && (count1 == 1 || count2 == 1)) { return "YES"; } } return "NO"; }
Seems like cookies are disabled on this browser, please enable them to open this website
I agree to HackerRank's Terms of Service and Privacy Policy.
Sherlock and the Valid String
You are viewing a single comment's thread. Return to all comments →
My C++ solution: