Please refer tho this question from hackerrank:
A bracket is considered to be any one of the following characters: (,
), {, }, [, or ].
Two brackets are considered to be a matched pair if the an opening
bracket (i.e., (, [, or {) occurs to the left of a closing bracket
(i.e., ), ], or }) of the exact same type. There are three types of
matched pairs of brackets: [], {}, and ().
A matching pair of brackets is not balanced if the set of brackets it
encloses are not matched. For example, {[(])} is not balanced because
the contents in between { and } are not balanced. The pair of square
brackets encloses a single, unbalanced opening bracket, (, and the
pair of parentheses encloses a single, unbalanced closing square
bracket, ]...
I have done the program as follows:
import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;
public class Solution {
static char findCorrBracket(char b)
{
if(b == '{')
{
return '}';
}
else if(b == '[')
{
return ']';
}
else
{
return ')';
}
}
// Complete the isBalanced function below.
static String isBalanced(String s) {
char a[] = new char[1000];
int top = 0,i=1;
a[0]=s.charAt(0);
char retBrack;
String result;
while(top!=-1 )
{
retBrack=findCorrBracket(s.charAt(top));
if(s.charAt(i)!=retBrack)
{
a[top]=s.charAt(i);
top=i;
}
else
{
top--;
}
i++;
if(i>=s.length()-1)
{
break;
}
}
System.out.println(top);
if(top==0)
{
result = "YES";
}
else
{
result = "NO";
}
return result;
}
private static final Scanner scanner = new Scanner(System.in);
public static void main(String[] args) throws IOException {
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));
int t = scanner.nextInt();
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
for (int tItr = 0; tItr < t; tItr++) {
String s = scanner.nextLine();
String result = isBalanced(s);
bufferedWriter.write(result);
bufferedWriter.newLine();
}
bufferedWriter.close();
scanner.close();
}
}
I have changed the code a little bit. It has made the program more readable. But still, the problem persists.
/******************************************************************************
Online Java Debugger.
Code, Run and Debug Java program online.
Write your code in this editor and press "Debug" button to debug program.
*******************************************************************************/
public class Main
{
static char findCorrBracket(char b)
{
if(b == '{')
{
return '}';
}
else if(b == '[')
{
return ']';
}
else
{
return ')';
}
}
// Complete the isBalanced function below.
static String isBalanced(String s) {
char a[] = new char[1000];
int top = 0,i=1;
a[0]=s.charAt(0);
char retBrack;
String result;
while(i<s.length())
{
retBrack=findCorrBracket(s.charAt(top));
if(s.charAt(i)!=retBrack)
{
top++;
a[top]=s.charAt(i);
}
else
{
top--;
}
i++;
}
System.out.println(top);
if(top==-1)
{
result = "YES";
}
else
{
result = "NO";
}
return result;
}
public static void main(String[] args) {
String s="{[]()}";
String result = isBalanced(s);
System.out.println(result);
}
}
It runs for few of the test cases, while for others it doesn't. How should I change the code?
Update - I've added the corrections I made as comments in the code.
static char findCorrBracket(char b)
{
if(b == '{')
{
return '}';
}
else if(b == '[')
{
return ']';
}
else if(b == '(')
{
//Use else if here instead of else, since otherwise '}',']','(' & ')' will all get the returned character value ')'
return ')';
} else {
return '_';
}
}
// Complete the isBalanced function below.
static String isBalanced(String s) {
char a[] = new char[1000];
int top = 0,i=1;
a[0]=s.charAt(0);
char retBrack;
String result;
while(i<s.length())
{
if(top == -1) {
//If the stack is empty, then we don't need to get the 'correct bracket' and check
//We can directly insert the character into the stack
top++;
a[top] = s.charAt(i);
} else {
//findCorrBracket from `a[top]`, not from `s.charAt(top)`
retBrack = findCorrBracket(a[top]);
if (s.charAt(i) != retBrack) {
top++;
a[top] = s.charAt(i);
} else {
top--;
}
}
i++;
}
System.out.println(top);
if(top==-1)
{
result = "YES";
}
else
{
result = "NO";
}
return result;
}
You loop should iterate through all the characters of the string. So, while (i<s.length()) should be moved from inside the while block to the condition.
The top value needs to be incremented, not set to the value of i.
// Complete the isBalanced function below.
static String isBalanced(String s) {
char a[] = new char[1000];
int top = 0,i=1;
a[0]=s.charAt(0);
char retBrack;
String result;
while(i<s.length() )
{
retBrack=findCorrBracket(s.charAt(top));
if(s.charAt(i)!=retBrack)
{
top++;
a[top]=s.charAt(i);
}
else
{
top--;
}
i++;
}
System.out.println(top);
if(top==-1)
{
result = "YES";
}
else
{
result = "NO";
}
return result;
}
P.S - There are a few improvements I could suggest,
As racraman suggested, use for loops instead of while, unless you need a do while.
Don't create a static array to use as a stack, use a Java collection (eg, ArrayList) to create a dynamic stack. This way, even if the string has more than a 1000 consecutive (, your code would work.
You've started off on the right path, using a stack and iterating over the string one character at a time. But your logic for each character doesn't seem to make any sense. Apparently it "works" if the input string meets some very specific conditions, but not in general. Something more like this (in pseudo-code) will work on any input:
for each character `c` in string `s`:
if `c` is an opening bracket:
PUSH`c` onto stack
else:
// `c` must be a closing bracket
if stack is EMPTY:
's` IS UNBALANCED
else:
POP top of stack into `b`
if `b` is not the correct matching opening bracket for `c`:
`s` IS UNBALANCED
end if
end if
end if
end for
if stack is EMPTY:
SUCCESS! (`s` is correctly balanced)
else:
`s` IS UNBALANCED
end if
Related
I have the shunting yard algorithm that I found online:
import java.util.HashMap;
import java.util.Map;
import java.util.Stack;
public class ShuntingYardAlgorithm {
private enum Operator {
ADD(1), SUBTRACT(2), MULTIPLY(3), DIVIDE(4);
final int precedence;
Operator(int p) {
precedence = p;
}
}
private Map<String, Operator> operatorMap = new HashMap<String, Operator>() {/**
*
*/
private static final long serialVersionUID = 1L;
{
put("+", Operator.ADD);
put("-", Operator.SUBTRACT);
put("*", Operator.MULTIPLY);
put("/", Operator.DIVIDE);
}};
private boolean isHigherPrec(String op, String sub) {
return (operatorMap.containsKey(sub) &&
operatorMap.get(sub).precedence >= operatorMap.get(op).precedence);
}
public String shuntingYard(String infix) {
StringBuilder output = new StringBuilder();
Stack<String> stack = new Stack<String>();
for (String token : infix.split("")) {
//operator
if (operatorMap.containsKey(token)) {
while ( ! stack.isEmpty() && isHigherPrec(token, stack.peek())) {
output.append(stack.pop()).append(' ');
}
stack.push(token);
}
//left parenthesis
else if (token.equals("(")) {
stack.push(token);
}
//right parenthesis
else if (token.equals(")")) {
while ( ! stack.peek().equals("(")) {
output.append(stack.pop()).append(' ');
}
stack.pop();
}
//digit
else {
output.append(token).append(' ');
}
}
while ( ! stack.isEmpty()) {
output.append(stack.pop()).append(' ');
}
return output.toString();
}
}
And the evaluator:
private static int evalRPN(String[] tokens) {
int returnValue = 0;
String operators = "+-*/";
Stack<String> stack = new Stack<String>();
for (String t : tokens) {
if (!operators.contains(t)) {
stack.push(t);
} else {
int a = Integer.valueOf(stack.pop());
int b = Integer.valueOf(stack.pop());
switch (t) {
case "+":
stack.push(String.valueOf(a + b));
break;
case "-":
stack.push(String.valueOf(b - a));
break;
case "*":
stack.push(String.valueOf(a * b));
break;
case "/":
stack.push(String.valueOf(b / a));
break;
}
}
}
returnValue = Integer.valueOf(stack.pop());
return returnValue;
}
And they work good so far but I have a problem with the evaluation where the delimiter is split by "", which does not allow two digit numbers, such as 23, or above. What can you suggest that I can do to improve the evaluation method?
String output = new ShuntingYardAlgorithm().shuntingYard(algExp);
algExp = output.replaceAll(" ", "");
String[] outputArray = algExp.split("");
return evalRPN(outputArray);
Such as I input: 256+3
result: 2 5 6 3 +
Evaluation: 6 + 3 = 9, ignores 2 and 5
Your shuntingYard function is discarding the contents of output when an operator or a parenthesis is encountered.
You need to add checks for contents of output before processing the current character.
if (operatorMap.containsKey(token)) {
// TODO: Check output here first, and create a token as necessary
while ( ! stack.isEmpty() && isHigherPrec(token, stack.peek())) {
output.append(stack.pop()).append(' ');
}
stack.push(token);
}
//left parenthesis
else if (token.equals("(")) {
// TODO: Check output here first, and create a token as necessary
stack.push(token);
}
//right parenthesis
else if (token.equals(")")) {
// TODO: Check output here first, and create a token as necessary
while ( ! stack.peek().equals("(")) {
output.append(stack.pop()).append(' ');
}
stack.pop();
}
Also, splitting using the empty string is equivalent to just iterating the String one character at a time. Iterating infix using toCharArray() might be more readable
for (char c : infix.toCharArray())
Example 1:
Input: S = "ab#c", T = "ad#c"
Output: true
Explanation: Both S and T become "ac".
Example 2:
Input: S = "ab##", T = "c#d#"
Output: true
Explanation: Both S and T become "".
Example 3:
Input: S = "a##c", T = "#a#c"
Output: true
Explanation: Both S and T become "c".
Example 4:
Input: S = "a#c", T = "b"
Output: false
Explanation: S becomes "c" while T becomes "b".
class Solution {
public boolean backspaceCompare(String S, String T) {
Stack<Character> stack1 = new Stack<Character>();
Stack<Character> stack2 = new Stack<Character>();
for(int i=0;i<S.length();i++){
if(S.charAt(i)!='#'){
stack1.push(S.charAt(i));
}else{
stack1.pop();
}
}
for(int j =0;j<T.length();j++){
if(T.charAt(j)!='#'){
stack2.push(S.charAt(j));
}else
stack2.pop();
}
if(stack1==stack2)
return true;
return false;
}
}
my output is false and answer should be true why is this not working?
The first mistake is pushing all the characters on the stack outside of the if statement.
Also you should check if stack is empty before removing items from it.
Otherwise EmptyStackException is thrown.
// stack1.push(S.charAt(i)); <-- remove this line
if (S.charAt(i)!='#') {
stack1.push(S.charAt(i));
}else if (!stack1.isEmpty()) { // <-- add this check
stack1.pop();
}
The second mistake is you can't use == to compare the contents of two stacks, use .equals method instead:
if(stack1.equals(stack2))
Answer by Joni correctly addresses the errors in the code, however there are some other issues I'd like to address:
You should use a helper method to eliminate repeating the same code.
You should use Deque instead of Stack. The javadoc says so.
Instead of using Stack/Deque, I'd recommend using StringBuilder, to prevent having to box the char values.
Something like this:
public boolean backspaceCompare(String s, String t) {
return applyBackspace(s).equals(applyBackspace(t));
}
private static String applyBackspace(String s) {
StringBuilder buf = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) != '#')
buf.append(s.charAt(i));
else if (buf.length() != 0)
buf.setLength(buf.length() - 1);
}
return buf.toString();
}
Your idea works, but it's expensive and unnecessary to copy the strings into stacks. If you work backwards from the end, no extra storage is necessary:
//given the string length or a valid character position, return
//the position of the previous valid character, or -1 if none
public static int previousCharPos(String s, int pos)
{
int bs=0; // number of backspaces to match
while(pos>0) {
--pos;
if (s.charAt(pos)=='#') {
++bs;
} else if (bs <= 0) {
return pos;
} else {
--bs;
}
}
return -1;
}
public static boolean backspaceCompare(String S, String T)
{
int spos = previousCharPos(S,S.length());
int tpos = previousCharPos(T,T.length());
while(spos >= 0 && tpos >= 0) {
if (S.charAt(spos) != T.charAt(tpos)) {
return false;
}
spos = previousCharPos(S,spos);
tpos = previousCharPos(T,tpos);
}
return spos == tpos;
}
I have written a java code to test if an expression is balanced or not, that is, this program checks if the characters '(', '{' and '[' have a corresponding delimiter or not. However I am unable to get the required answer. There is something wrong and I am unable to figure it out and hence would need your help. Here is the code.
package z_Stack_InfixToPostfix;
import java.util.Stack;
public class Driver_InfixToPostfix {
public static void main(String[] args) {
String s="(a+b)";
System.out.println(checkBalance(s));
}
public static boolean checkBalance(String expression){
boolean isBalanced=true;
Stack<Character> myStack=new Stack<Character>();
int length=expression.length();
int i=0;
while(isBalanced && i<length){
switch(expression.charAt(i)){
case '(': case '{': case '[' :
myStack.push(expression.charAt(i));
break;
case ')': case '}': case ']':
if(myStack.isEmpty()){
isBalanced=false;
}
else{
char opendelimiter=myStack.pop();
if(opendelimiter!=expression.charAt(i)){
isBalanced=false;
}
}
break;
}
i++;
}
if(!myStack.isEmpty()){
isBalanced=false;
}
return isBalanced;
}
}
char opendelimiter=myStack.pop();
if(opendelimiter!=expression.charAt(i)){
isBalanced=false;
}
Here you should check
if(openedDeimilter == '('){
if(expression.charAt(i)!=')'){
isBalanced=false;
//break;
}
}else if(openedDeimilter == '['){
if(expression.charAt(i)!=']'){
isBalanced=false;
//break;
}
}else {
if(expression.charAt(i)!='}'){
isBalanced=false;
//break;
}
}
Also once isBalanced is set to false you can skip iterating the remaining string, if it suits you.
What about a different approach using only the length of your expression without each parentheses? This will let you not use the Stack class and should be more efficient for longer expression
public static boolean checkBalance(String expression) {
String[] parentheses = new String[]{"\\(|\\)","\\[|\\]","\\{|\\}"};
int length = expression.length();
for(int i=0; i<parentheses.length; i++) {
int newLength = expression.replaceAll(parentheses[i], "").length();
int diff = length - newLength;
if(diff % 2 != 0) {
return false;
}
}
return true;
}
The double backslash are used to escape each parentheses because they are special characters
This part is wrong:
if(opendelimiter!=expression.charAt(i)){
isBalanced=false;
}
You check if two chars are equal, but the correct check should match the 2 corresponding chars: [ - ], ( - ) and { - }
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
char exp[1028];
char ext[1028];
int top = -1;
//-----------------------------------------------------------------------------
push(char x){
top++;
ext[top]=x;
}
//-----------------------------------------------------------------------------------------
void pop(){
top--;
}
//--------------------------------------------------------------------------------------
main()
{
int ans;
char in='{';
char it='[';
char ie='(';
char an;'}';
char at=']';
char ae=')';
printf("\nenter your expression\n");
gets(exp);
int j=strlen(exp);
int i;
for(i=0;i<=j;i++){
if(exp[i] == in || exp[i] == it || exp[i]==ie){
push(exp[i]);
}
if(exp[i] == an ||exp[i]== at || exp[i]==ae){
pop();
}
}
if(top == -1){
printf("\nexp is balanced\n");
}
else{
printf("\nexp is unbalanced");
}
}
package edu.bsu.cs121.mamurphy;
import java.util.Stack;
public class Checker {
char openPara = '(';
char openBracket = '[';
char openCurly = '{';
char openArrow = '<';
char closePara = ')';
char closeBracket = ']';
char closeCurly = '}';
char closeArrow = '>';
public boolean checkString(String stringToCheck) {
Stack<Character> stack = new Stack<Character>();
for (int i = 0; i < stringToCheck.length(); i++) {
char c = stringToCheck.charAt(i);
if (c == openPara || c == openBracket || c == openCurly || c == openArrow) {
stack.push(c);
System.out.println(stack);
;
}
if (c == closePara) {
if (stack.isEmpty()) {
System.out.println("Unbalanced");
break;
} else if (stack.peek() == openPara) {
stack.pop();
} else if (stack.size() > 0) {
System.out.println("Unbalanced");
break;
}
}
if (c == closeBracket) {
if (stack.isEmpty()) {
System.out.println("Unbalanced");
break;
} else if (stack.peek() == openBracket) {
stack.pop();
} else if (stack.size() > 0) {
System.out.println("Unbalanced");
break;
}
}
if (c == closeCurly) {
if (stack.isEmpty()) {
System.out.println("Unbalanced");
break;
} else if (stack.peek() == openCurly) {
stack.pop();
} else if (stack.size() > 0) {
System.out.println("Unbalanced");
break;
}
}
if (c == closeArrow) {
if (stack.isEmpty()) {
System.out.println("Unbalanced");
break;
} else if (stack.peek() == openArrow) {
stack.pop();
} else if (stack.size() > 0) {
System.out.println("Unbalanced");
break;
}
}
}
return false;
}
}
I am currently trying to create a program where I check to see if a string is balanced or not. A string is balanced if and only if each opening character: (, {, [, and < have a matching closing character: ), }, ], and > respectively.
What happens is when checking through the string, if an opening character is found, it is pushed into a stack, and it checks to see if there is the appropriate closing character.
If there is a closing character before the opening character, then that automatically means that the string is unbalanced. Also, the string is automatically unbalanced if after going to the next character there is something still inside of the stack.
I tried to use
else if (stack.size() > 0) {
System.out.println("Unbalanced");
break;
}
as a way of seeing if the stack still had anything in it, but it still isn't working for me. Any advice on what to do?
For example, if the string input were ()<>{() then the program should run through like normal until it gets to the single { and then the code should realize that the string is unbalanced and output Unbalanced.
For whatever reason, my code does not do this.
The following logic is flawed (emphasis mine):
For example, if the string input were ()<>{() then the program should run through like normal until it gets to the single { and then the code should realize that the string is unbalanced and output Unbalanced.
In fact, the code can't conclude that the string is unbalanced until it has scanned the entire string and established that the { has no matching }. For all it knows, the full input could be ()<>{()} and be balanced.
To achieve this, you need to add a check that ensures that the stack is empty after the entire string has been processes. In your example, it would still contain the {, indicating that the input is not balanced.
I took a shot at answering this. My solutions returns true if the string is balanced and enforces opening/closing order (ie ({)} returns false). I started with your code and tried to slim it down.
import java.util.HashMap;
import java.util.Map;
import java.util.Stack;
public class mamurphy {
private static final char openPara = '(';
private static final char openBracket = '[';
private static final char openCurly = '{';
private static final char openArrow = '<';
private static final char closePara = ')';
private static final char closeBracket = ']';
private static final char closeCurly = '}';
private static final char closeArrow = '>';
public static void main(String... args) {
System.out.println(checkString("{}[]()90<>"));//true
System.out.println(checkString("(((((())))"));//false
System.out.println(checkString("((())))"));//false
System.out.println(checkString(">"));//false
System.out.println(checkString("["));//false
System.out.println(checkString("{[(<>)]}"));//true
System.out.println(checkString("{[(<>)}]"));//false
System.out.println(checkString("( a(b) (c) (d(e(f)g)h) I (j<k>l)m)"));//true
}
public static boolean checkString(String stringToCheck) {
final Map<Character, Character> closeToOpenMap = new HashMap<>();
closeToOpenMap.put(closePara, openPara);
closeToOpenMap.put(closeBracket, openBracket);
closeToOpenMap.put(closeCurly, openCurly);
closeToOpenMap.put(closeArrow, openArrow);
Stack<Character> stack = new Stack<>();
final char[] stringAsChars = stringToCheck.toCharArray();
for (int i = 0; i < stringAsChars.length; i++) {
final char current = stringAsChars[i];
if (closeToOpenMap.values().contains(current)) {
stack.push(current); //found an opening char, push it!
} else if (closeToOpenMap.containsKey(current)) {
if (stack.isEmpty() || closeToOpenMap.get(current) != stack.pop()) {
return false;//found closing char without correct opening char on top of stack
}
}
}
if (!stack.isEmpty()) {
return false;//still have opening chars after consuming whole string
}
return true;
}
}
Here's an alternate approach:
private static final char[] openParens = "[({<".toCharArray();
private static final char[] closeParens = "])}>".toCharArray();
public static boolean isBalanced(String expression){
Deque<Character> stack = new ArrayDeque<>();
for (char c : expression.toCharArray()){
for (int i = 0; i < openParens.length; i++){
if (openParens[i] == c){
// This is an open - put it in the stack
stack.push(c);
break;
}
if (closeParens[i] == c){
// This is a close - check the open is at the top of the stack
if (stack.poll() != openParens[i]){
return false;
}
break;
}
}
}
return stack.isEmpty();
}
It simplifies the logic to have two corresponding arrays of open and close symbols. You could also do this with even and odd positions in one array - ie. "{}<>", for example:
private static final char[] symbols = "[](){}<>".toCharArray();
public static boolean isBalanced(String expression){
Deque<Character> stack = new ArrayDeque<>();
for (char c : expression.toCharArray()){
for (int i = 0; i < symbols.length; i += 2){
if (symbols[i] == c){
// This is an open - put it in the stack
stack.push(c);
break;
}
if (symbols[i + 1] == c){
// This is a close - check the open is at the top of the stack
if (stack.poll() != symbols[i]){
return false;
}
break;
}
}
}
return stack.isEmpty();
}
Note that poll returns null if the stack is empty, so will correctly fail the equality comparison if we run out of stack.
For example, if the string input were ()<>{() then the program should run through like normal until it gets to the single { and then the code should realize that the string is unbalanced and output Unbalanced.
It is not clear by your example whether the boundaries can be nested like ([{}]). If they can, that logic will not work, as the whole string has to be consumed to be sure any missing closing-chars aren't at the end, and so, the string cannot be reliably deemed unbalanced at the point you indicate.
Here is my take on your problem:
BalanceChecker class:
package so_q33378870;
import java.util.Stack;
public class BalanceChecker {
private final char[] opChars = "([{<".toCharArray();
private final char[] edChars = ")]}>".toCharArray();
//<editor-fold defaultstate="collapsed" desc="support functions">
public boolean isOPChar(char c) {
for (char checkChar : opChars) {
if (c == checkChar) {
return true;
}
}
return false;
}
public boolean isEDChar(char c) {
for (char checkChar : edChars) {
if (c == checkChar) {
return true;
}
}
return false;
}
//NOTE: Unused.
// public boolean isBoundaryChar(char c) {
// boolean result;
// if (result = isOPChar(c) == false) {
// return isEDChar(c);
// } else {
// return result;
// }
// }
public char getOpCharFor(char c) {
for (int i = 0; i < edChars.length; i++) {
if (c == edChars[i]) {
return opChars[i];
}
}
throw new IllegalArgumentException("The character (" + c + ") received is not recognized as a closing boundary character.");
}
//</editor-fold>
public boolean isBalanced(char[] charsToCheck) {
Stack<Character> checkStack = new Stack<>();
for (int i = 0; i < charsToCheck.length; i++) {
if (isOPChar(charsToCheck[i])) {
//beginning char found. Add to top of stack.
checkStack.push(charsToCheck[i]);
} else if (isEDChar(charsToCheck[i])) {
if (checkStack.isEmpty()) {
//ending char found without beginning chars on the stack. UNBALANCED.
return false;
} else if (getOpCharFor(charsToCheck[i]) == checkStack.peek()) {
//ending char found matches last beginning char on the stack. Pop and continue.
checkStack.pop();
} else {
//ending char found, but doesn't match last beginning char on the stack. UNBALANCED.
return false;
}
}
}
//the string is balanced if and only if the stack is empty at the end.
return checkStack.empty();
}
public boolean isBalanced(String stringToCheck) {
return isBalanced(stringToCheck.toCharArray());
}
}
Main class (used for testing):
package so_q33378870;
public class main {
private static final String[] tests = {
//Single - Balanced.
"()",
//Single - Unbalanced by missing end.
"(_",
//Multiple - Balanced.
"()[]{}<>",
//Multiple - Unbalanced by missing beginning.
"()[]_}<>",
//Nested - Balanced.
"([{<>}])",
//Nested - Unbalanced by missing end.
"([{<>}_)",
//Endurance test - Balanced.
"the_beginning (abcd) divider (a[bc]d) divider (a[b{c}d]e) divider (a[b{c<d>e}f]g) the_end"
};
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
BalanceChecker checker = new BalanceChecker();
for (String s : tests) {
System.out.println("\"" + s + "\" is " + ((checker.isBalanced(s)) ? "BALANCED!" : "UNBALANCED!"));
}
}
}
I have four classes.
One contains my linkedstack setup
One is infixtopostfix for prioritization and conversion
Parenthesis for matching
Postfix for evaluation
I have setup almost everything here but it is still returning false anyway I put it.
On another note my equals on !stackMatch.pop().equals(c) is not working due to it being a object type with '!' being a problem.
My programs are simple and straight forward:
LinkedStack.java
public class LinkedStack implements StackInterface {
private Node top;
public LinkedStack() {
top = null;
} // end default constructor
public boolean isEmpty() {
return top == null;
} // end isEmpty
public void push(Object newItem) {
Node n = new Node();
n.setData(newItem);
n.setNext(top);
top = n;
} // end push
public Object pop() throws Exception {
if (!isEmpty()) {
Node temp = top;
top = top.getNext();
return temp.getData();
} else {
throw new Exception("StackException on pop: stack empty");
} // end if
} // end pop
public Object peek() throws Exception {
if (!isEmpty()) {
return top.getData();
} else {
throw new Exception("StackException on peek: stack empty");
} // end if
} // end peek
} // end LinkedStack
InfixToPostfix.java
import java.util.*;
public class InfixToPostfix {
Parenthesis p = new Parenthesis();
LinkedStack stack = new LinkedStack();
String token = ""; // each token of the string
String output = ""; // the string holding the postfix expression
Character topOfStackObject = null; // the top object of the stack, converted to a Character Object
char charValueOfTopOfStack = ' '; // the primitive value of the Character object
/**
* Convert an infix expression to postfix. If the expression is invalid, throws an exception.
* #param s the infix expression
* #return the postfix expression as a string
* hint: StringTokenizer is very useful to this iteratively
*/
//public String convertToPostfix(String s) throws Exception {
//}
private boolean isOperand (char c){
return ((c>= '0' && c <= '9') || (c >= 'a' && c<= 'z'));
}
public void precedence(char curOp, int val) throws Exception {
while (!stack.isEmpty()) {
char topOp = (Character) stack.pop();
// charValueOfTopOfStack = topOfStackObject.charValue();
if (topOp == '(') {
stack.push(topOp);
break;
}// it's an operator
else {// precedence of new op
int prec2;
if (topOp == '+' || topOp == '-') {
prec2 = 1;
} else {
prec2 = 2;
}
if (prec2 < val) // if prec of new op less
{ // than prec of old
stack.push(topOp); // save newly-popped op
break;
} else // prec of new not less
{
output = output + topOp; // than prec of old
}
}
}
}
Parenthesis.java
import java.util.*;
public class Parenthesis{
private LinkedStack stack = new LinkedStack();
private Object openBrace;
private String outputString;
/**
* Determine if the expression has matching parenthesis using a stack
*
* #param expr the expression to be evaluated
* #return returns true if the expression has matching parenthesis
*/
public boolean match(String expr) {
LinkedStack stackMatch = new LinkedStack();
for(int i=0; i < expr.length(); i++) {
char c = expr.charAt(i);
if(c == '(')
stackMatch.push(c);
else if(c == ')'){
if (stackMatch.isEmpty() || !stackMatch.pop().equals(c))
return false;
}
}
return stackMatch.isEmpty();
}
}
Just wanted to give you all of it so you could help me. I have tests written already just struggling with the parenthesis problem of pushing it on the stack but unable to compare it to the closing parenthesis so it can check if there is enough while checking to be sure it is not empty.
The problem probably is, that you are trying to test if matching ( is currently on top of the stack when ) comes, but in c is acctual character, ), so you test if ) is on top of stack, not ( as you should.