Created
February 25, 2019 16:23
-
-
Save bingli224/70b1d8ca5ebc27cc442d2f73c5d4764e to your computer and use it in GitHub Desktop.
This file contains hidden or 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
#include <bits/stdc++.h> | |
using namespace std; | |
// Complete the isValid function below. | |
string isValid(string s) { | |
// 23:21 THA 25/02/2019 | |
// by BingLi224 | |
// Reference: https://www.hackerrank.com/challenges/sherlock-and-valid-string/problem | |
unsigned long count [ 26 ] = { 0 }; | |
int idx = 0; | |
unsigned long sz = s.length ( ); | |
for ( idx = 0; idx < sz; idx ++ ) { | |
count [ s [ idx ] - 'a' ] ++; | |
} | |
// skip existing data | |
for ( idx = 0; idx < 26 && count [ idx ] == 0; idx ++ ) { } | |
if ( idx >= 26 ) | |
return "YES"; // no data | |
// evaluate | |
unsigned long minCount, maxCount, min, max; | |
minCount = maxCount = count [ idx ]; | |
min = max = 1; | |
for ( ++ idx; idx < 26; idx ++ ) { | |
unsigned long c = count [ idx ]; | |
if ( c <= 0 ) | |
continue; | |
else if ( c == minCount ) { | |
min ++; | |
if ( c == maxCount ) { | |
max ++; | |
} else if ( ( max > 1 || maxCount - minCount > 1 ) && ( minCount > 1 || min > 1 ) ) { // && min > 1 | |
return "NO"; | |
} | |
} else if ( c == maxCount ) { | |
max ++; | |
if ( minCount > 1 || min > 1 ) // && max > 1 | |
return "NO"; | |
} else if ( c < minCount ) { | |
if ( minCount < maxCount ) // && ( max > 1 || min > 1 ) ) //&& min > 0 ) | |
return "NO"; // too high range | |
else if ( maxCount - c > 1 && c > 1 ) | |
return "NO"; | |
minCount = c; | |
min = 1; | |
} else if ( c > maxCount ) { | |
if ( minCount < maxCount ) //&& max > 0 && min > 0 ) | |
return "NO"; // too high range | |
else if ( c - minCount > 1 && ( min > 1 || minCount > 1 ) ) | |
return "NO"; | |
maxCount = c; | |
max = 1; | |
} else { | |
// out of scope | |
//cout << minCount << " " << min << " | " << maxCount << " " << max << endl; | |
return "NO"; | |
} | |
} | |
return "YES"; | |
} | |
int main() | |
{ | |
ofstream fout(getenv("OUTPUT_PATH")); | |
string s; | |
getline(cin, s); | |
string result = isValid(s); | |
fout << result << "\n"; | |
fout.close(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment