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.
My Solution:
import java.util.*;
class Solution{
public static void main(String[] argh)
{
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
String input=sc.next();
//Complete the code
//check if input string is balanced
boolean isBalanced = isBalanced(input);
//Print the result true or false
if(isBalanced)
{
System.out.println("true");
}
else
{
System.out.println("false");
}
}
sc.close();
}
// Method to check if a string containing parentheses, brackets, and braces is balanced
public static boolean isBalanced(String s)
{
// Initialize a stack to hold opening symbols
Stack<Character>stack = new Stack<>();
// Iterate through each character in the string
for(char ch : s.toCharArray())
{
// If the character is an opening symbol, push it onto the stack
if(ch == '(' || ch == '{' || ch == '[')
{
stack.push(ch);
}
// If the character is a closing symbol
else if(ch == ')' || ch == '}' || ch == ']')
{
// Check if the stack is empty
if(stack.isEmpty())
{
return false; // Unmatched closing symbol
}
// Pop the top element from the stack
char top = stack.pop();
// Check if the top element matches the closing symbol
if(!isMatchingPair(top, ch))
{
return false; // Mismatched pair
}
}
}
// The string is balanced if the stack is empty at the end
return stack.isEmpty();
}
// Method to check if the opening and closing symbols match
public static boolean isMatchingPair(char open, char close)
{
return(open == '(' && close == ')')||
(open == '{' && close == '}')||
(open == '[' && close == ']');
}
}
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 →
My Solution: import java.util.*; class Solution{ public static void main(String[] argh) { Scanner sc = new Scanner(System.in);
while (sc.hasNext()) { String input=sc.next(); //Complete the code //check if input string is balanced boolean isBalanced = isBalanced(input);