We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
You had some excellent suggestions here. However, I've got some as well ...
**
Use toCharArray () to make iterating over the String cleaner looking.
**
I would keep the ArrayDeque in the method's scope instead that of the class since that's the only place where it's used.
**
Instead of using size () == 0, use isEmpty () it's more readable.
**
Finally, once you fail, there is no longer a reason to continue the routine, just exit with false immediately.
**
Finally, you could also ignore characters other than the 6 we're looking for instead of failing. I've kept the failure logic below.
private static boolean isBalanced (String s) {
final ArrayDeque<Character> stack = new ArrayDeque<> ();
final char[] chars = s.toCharArray ();
for (char c : chars) {
// Matching character, . means not initialized
char mc = '.';
switch (c) {
case '(':
case '{':
case '[':
stack.addFirst (c);
break;
case ')':
mc = '(';
case '}':
if (mc == '.') mc = '{';
case ']':
if (mc == '.') mc = '[';
if (stack.isEmpty () ||
stack.removeFirst () != mc) {
return false;
}
break;
default:
// Any other character is bad input data
return false;
}
}
return stack.isEmpty ();
}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Java Stack
You are viewing a single comment's thread. Return to all comments →
You had some excellent suggestions here. However, I've got some as well ...
**
Use toCharArray () to make iterating over the String cleaner looking.
**
I would keep the ArrayDeque in the method's scope instead that of the class since that's the only place where it's used.
**
Instead of using size () == 0, use isEmpty () it's more readable.
**
Finally, once you fail, there is no longer a reason to continue the routine, just exit with false immediately.
**
Finally, you could also ignore characters other than the 6 we're looking for instead of failing. I've kept the failure logic below.