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.
private static Boolean cMatch(Character l, Character c){
return ( l == '(' && c == ')')
|| ( l == '[' && c == ']')
|| ( l == '{' && c == '}');
}
public static String isBalanced(String s) {
// Write your code here
Stack stack = new Stack<>();
stack.push('#');
for (int i = 0; i < s.length(); i++){
Character c = s.charAt(i);
if ( c == '(' || c == '[' || c == '{'){
stack.push(c);
}else{
Character last = stack.peek();
if ( cMatch(last, c )){
stack.pop();
}else{
return "NO";
}
}
}
if (stack.size() == 1){
return "YES";
}
return "NO";
}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Balanced Brackets
You are viewing a single comment's thread. Return to all comments →
private static Boolean cMatch(Character l, Character c){ return ( l == '(' && c == ')') || ( l == '[' && c == ']') || ( l == '{' && c == '}'); } public static String isBalanced(String s) { // Write your code here Stack stack = new Stack<>(); stack.push('#');