I am trying to create a program that takes a string as an argument into its constructor. I need a method that checks whether the string is a balanced parenthesized expression. It needs to handle ( { [ ] } ) each open needs to balance with its corresponding closing bracket. For example a user could input [({})] which would be balanced and }{ would be unbalanced. This doesn't need to handle letters or numbers. I need to use a stack to do this.
I was given this pseudocode but can not figure how to implement it in java. Any advice would be awesome.
Update- sorry forgot to post what i had so far. Its all messed up because at first i was trying to use char and then i tried an array.. im not exactly sure where to go.
import java.util.*;
public class Expression
{
Scanner in = new Scanner(System.in);
Stack<Integer> stack = new Stack<Integer>();
public boolean check()
{
System.out.println("Please enter your expression.");
String newExp = in.next();
String[] exp = new String[newExp];
for (int i = 0; i < size; i++)
{
char ch = exp.charAt(i);
if (ch == '(' || ch == '[' || ch == '{')
stack.push(i);
else if (ch == ')'|| ch == ']' || ch == '}')
{
//nothing to match with
if(stack.isEmpty())
{
return false;
}
else if(stack.pop() != ch)
{
return false;
}
}
}
if (stack.isEmpty())
{
return true;
}
else
{
return false;
}
}
}
A string having brackets is said to be balanced if: A matching closing bracket occurs to the right of each corresponding opening bracket. Brackets enclosed within balanced brackets should also be balanced. It should not contain any non-bracket character.
Valid Parentheses solution in Java We iterate over the characters of the string, and for every iteration: if the current character is an opening bracket, we push it in the stack. if the character is a closing bracket, we pop the stack and check if the top of the stack contains its corresponding opening bracket or not.
I hope this code can help:
import java.util.Stack; public class BalancedParenthensies { public static void main(String args[]) { System.out.println(balancedParenthensies("{(a,b)}")); System.out.println(balancedParenthensies("{(a},b)")); System.out.println(balancedParenthensies("{)(a,b}")); } public static boolean balancedParenthensies(String s) { Stack<Character> stack = new Stack<Character>(); for(int i = 0; i < s.length(); i++) { char c = s.charAt(i); if(c == '[' || c == '(' || c == '{' ) { stack.push(c); } else if(c == ']') { if(stack.isEmpty() || stack.pop() != '[') { return false; } } else if(c == ')') { if(stack.isEmpty() || stack.pop() != '(') { return false; } } else if(c == '}') { if(stack.isEmpty() || stack.pop() != '{') { return false; } } } return stack.isEmpty(); } }
public static boolean isBalanced(String expression) { if ((expression.length() % 2) == 1) return false; else { Stack<Character> s = new Stack<>(); for (char bracket : expression.toCharArray()) switch (bracket) { case '{': s.push('}'); break; case '(': s.push(')'); break; case '[': s.push(']'); break; default : if (s.isEmpty() || bracket != s.peek()) { return false;} s.pop(); } return s.isEmpty(); } } public static void main(String[] args) { Scanner in = new Scanner(System.in); String expression = in.nextLine(); boolean answer = isBalanced(expression); if (answer) { System.out.println("YES");} else { System.out.println("NO");} }
The pseudo code equivalent java implementation of the algorithm is java is as follows.
import java.util.HashMap;
import java.util.Map;
import java.util.Stack;
/**
* @author Yogen Rai
*/
public class BalancedBraces
{
public static void main(String[] args) {
System.out.println(isBalanced("{{}}") ? "YES" : "NO"); // YES
System.out.println(isBalanced("{{}(") ? "YES" : "NO"); // NO
System.out.println(isBalanced("{()}") ? "YES" : "NO"); // YES
System.out.println(isBalanced("}{{}}") ? "YES" : "NO"); // NO
}
public static boolean isBalanced(String brackets) {
// set matching pairs
Map<Character, Character> braces = new HashMap<>();
braces.put('(', ')');
braces.put('[',']');
braces.put('{','}');
// if length of string is odd, then it is not balanced
if (brackets.length() % 2 != 0) {
return false;
}
// travel half until openings are found and compare with
// remaining if the closings matches
Stack<Character> halfBraces = new Stack();
for(char ch: brackets.toCharArray()) {
if (braces.containsKey(ch)) {
halfBraces.push(braces.get(ch));
}
// if stack is empty or if closing bracket is not equal to top of stack,
// then braces are not balanced
else if(halfBraces.isEmpty() || ch != halfBraces.pop()) {
return false;
}
}
return halfBraces.isEmpty();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With