import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); // Read the input string String input = sc.nextLine(); BalancedParentheses bp = new BalancedParentheses(); // Print whether the string has balanced parentheses System.out.println(bp.hasBalancedParentheses(input)); } } class BalancedParentheses { public boolean hasBalancedParentheses(String input) { // Remove this and implement code throw new UnsupportedOperationException(); } }
import java.util.*;
public class Main
{
public static void main(String[] args)
{ Scanner sc = new Scanner(System.in);
// Read the input string
String input = sc.nextLine();
BalancedParentheses bp = new BalancedParentheses();
// Print whether the string has balanced parentheses
System.out.println(bp.hasBalancedParentheses(input));
}
}
class BalancedParentheses
{ public boolean hasBalancedParentheses(String input)
{ // Remove this and implement code throw new
UnsupportedOperationException();
if (input.isEmpty())
return true;
Stack<Character> stack = new Stack<Character>();
for (int i = 0; i < input.length(); i++)
{
char current = input.charAt(i);
if (current == '{' || current == '(' || current == '[')
{
stack.push(current);
}
if (current == '}' || current == ')' || current == ']')
{
if (stack.isEmpty())
return false;
char last = stack.peek();
if (current == '}' && last == '{' || current == ')'
&& last == '(' || current == ']' && last ==
'[')
stack.pop();
else
return false;
}
}
return stack.isEmpty()?true:false;
}
}
Get Answers For Free
Most questions answered within 1 hours.