Last active
December 11, 2015 21:28
-
-
Save paldepind/4662669 to your computer and use it in GitHub Desktop.
C++ solution the problem "Balanced Smileys" in the Facebook Hackecup 2013.
No stacks, no recursion. Complexity is O(n).
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
bool isBalanced(const string message) { | |
int paransOpen = 0; | |
int maybeOpen = 0; | |
int maybeClosed = 0; | |
char prevChar = 0; | |
string::const_iterator iter; | |
for (iter = message.begin(); iter < message.end(); iter++) { | |
if (*iter == '(') { | |
if (prevChar == ':') { | |
maybeOpen++; | |
} else { | |
paransOpen++; | |
} | |
} else if (*iter == ')') { | |
if (prevChar == ':') { | |
if (paransOpen > 0) { // <-- Untested fix to problem pointed out to me by Angelo Di Pilla | |
maybeClosed++; | |
} | |
} else { | |
paransOpen--; | |
} | |
} else if (!isalpha(*iter) && *iter != ':' && *iter != ' ') { | |
return false; | |
} | |
if (paransOpen + maybeOpen < 0) { | |
return false; | |
} | |
prevChar = *iter; | |
} | |
if (paransOpen + maybeOpen >= 0 && | |
paransOpen - maybeClosed <= 0) { | |
return true; | |
} else { | |
return false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment