Converting infix to postfix and getting an EmptyStackException - java

I am working on a project to convert infix notation to postfix notation and then evaluate the equation. I established the precedence for each operator. When I use the ConvertToPostfix method I get the Exception. I understand the concept of the reverse polish notation calculator and I am just struggling with doing it with my code. I am new to stack overflow so if there is something that may seem a little confusing just let me know and ill try to edit it.
import java.util.Stack;
public class RPNCalctest {
public static void main( String[] args) throws InvalidInfixEquationException {
String example= "3+4/3*2"; //postfix notation would be 3 4 3 / 2 * +
System.out.println(ConvertToPostfix(example));
// TODO
}
//establish precedence
static int precedence(String c){
switch(c){
case"+":
case"-":
return 1;
case"*":
case"/":
return 2;
case")":
return 3;
case"(":
return 4;
default:
return -1;
}
}
// Precondition: every operator/operand will be separated by at least one space
public static String ConvertToPostfix(String infix) throws InvalidInfixEquationException {
String[] tokens = infix.split(" ");
String result = "";
Stack<String> stack = new Stack<>();
for (int i = 0; i < tokens.length; i++) {
String current = tokens[i];
if (precedence(current) > 0) {
while (!stack.isEmpty() && precedence(stack.peek()) >= precedence(current)) {
result += stack.pop() + " ";
}
stack.push(current);
} else {
result += current + " ";
}
}
for (int i = 0; i <= stack.size(); i++) {
result += stack.pop();
}
return result;
}
}
Exception in thread "main" java.util.EmptyStackException
at java.base/java.util.Stack.peek(Stack.java:101)
at java.base/java.util.Stack.pop(Stack.java:83)
at RPNCalctest.ConvertToPostfix(RPNCalctest.java:50)
at RPNCalctest.main(RPNCalctest.java:7)

Your problem is here. You pop off one more entry than there is.
for (int i = 0; i <= stack.size(); i++) {
result += stack.pop();
}
Consider size=2. You execute the loop for i=0, 1, 2.
I assume that the 'pop' line is line 53 as indicated in the stack trace, so for future reference, that's useful debugging info and you should use it.
It might be clearer if that loop were coded:
while (!stack.isEmpty()) {
result += stack.pop();
}
No need for the extraneous variable 'i'.

Related

Decode String in Java

I am trying to convert this Python Solution in Java. For some reason, my Java Solution is not working. How can this be done correctly?
https://leetcode.com/problems/decode-string/description/
Given an encoded string, return its decoded string. The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times. Note that k is guaranteed to be a positive integer.
You may assume that the input string is always valid; there are no extra white spaces, square brackets are well-formed, etc. Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, k. For example, there will not be input like 3a or 2[4].
The test cases are generated so that the length of the output will never exceed 105.
Example 1:
Input: s = "3[a]2[bc]"
Output: "aaabcbc"
Example 2:
Input: s = "3[a2[c]]"
Output: "accaccacc"
Python Solution:
class Solution:
def decodeString(self, s: str) -> str:
stack = []
for char in s:
if char is not "]":
stack.append(char)
else:
sub_str = ""
while stack[-1] is not "[":
sub_str = stack.pop() + sub_str
stack.pop()
multiplier = ""
while stack and stack[-1].isdigit():
multiplier = stack.pop() + multiplier
stack.append(int(multiplier) * sub_str)
return "".join(stack)
Java Attempt:
class Solution {
public String decodeString(String s) {
Deque<String> list = new ArrayDeque<String>();
String subword = "";
String number = "";
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) != ']' ) {
list.add(String.valueOf(s.charAt(i)));
}
else {
subword = "";
while (list.size() > 0 && !list.getLast().equals("[") ) {
subword = list.pop() + subword;
}
if (list.size() > 0) list.pop();
number = "";
while (list.size() > 0 && isNumeric(list.getLast())){
number = list.pop() + number;
}
for (int j = 1; (isNumeric(number) && j <= Integer.parseInt(number)); j++) list.add(subword);
}
}
return String.join("", list);
}
public static boolean isNumeric(String str) {
try {
Double.parseDouble(str);
return true;
} catch(NumberFormatException e){
return false;
}
}
}
The reason why your posted code is not working is because the pop() method in python removes the last element by default.
But in Java, the ArrayDeque class's pop() method removes the first element.
In order to emulate the python code with the ArrayDeque, you'll need to use the removeLast() method of the ArrayDeque instance instead.
public class Solution{
public static String decodeString(String s) {
StringBuilder stack = new StringBuilder();
for(char c : s.toCharArray()) {
if(c != ']') {
stack.append(c);
} else {
StringBuilder sub_str = new StringBuilder();
while(stack.charAt(stack.length() - 1) != '[') {
sub_str.insert(0, stack.charAt(stack.length() - 1));
stack.deleteCharAt(stack.length() - 1);
}
stack.deleteCharAt(stack.length() - 1);
StringBuilder multiplier = new StringBuilder();
while(stack.length() > 0 && Character.isDigit(stack.charAt(stack.length() - 1))) {
multiplier.insert(0, stack.charAt(stack.length() - 1));
stack.deleteCharAt(stack.length() - 1);
}
for(int i = 0; i < Integer.parseInt(multiplier.toString()); i++) {
stack.append(sub_str);
}
}
}
return stack.toString();
}
public static void main(String[] args) {
System.out.println( decodeString("3[a2[c]]"));
//Output: "accaccacc"
System.out.println( decodeString("3[a]2[bc]"));
//Output: "aaabcbc"
}
}

Infix to Postfix Notation Parentheses issue

So I am currently working on a project to convert infix to postfix notation and I am almost finished with the project. It correctly converts infix to postfix until I try adding parentheses it ends up incorrectly formatted.
static int precedence(String c){
switch(c){
case"+":
case"-":
return 1;
case"*":
case"/":
return 2;
default:
return -1;
}
}
I believe that this next part the code is good because everything works correctly without parentheses.
// Precondition: every operator/operand will be separated by at least one space
public static String ConvertToPostfix(String infix) throws InvalidInfixEquationException
{
String[] tokens = infix.split("");
String result= " ";
Stack<String> stack= new Stack<>();
for(int i = 0; i<tokens.length; i++){
String current = tokens[i];
if(precedence(current)>0){
while(!stack.isEmpty() && precedence(stack.peek())>= precedence(current)){
result += stack.pop() + " ";
}
stack.push(current);
} else if(!stack.isEmpty()&& precedence(stack.peek())<= precedence(current)){
result += stack.pop() + " ";
}
I believe that the issue I'm having is with the next part of my code involving manipulating the parentheses.
else if(current== ")"){
String s = stack.pop();
while(s !="("){
result += s;
s= stack.pop();
}
} else if(current == "("){
stack.push(current);
}
else {
result += current + " ";
}
}
for(int i=0;i <= stack.size(); i++){
result+= stack.pop() + " ";
}
return result;
}
This is my main method and I have included an example output.
import java.util.Stack;
public class RPNcalc {
public static void main( String[] args) throws InvalidInfixEquationException, InvalidPostfixEquationException {
String result= "(3+4)/3*2"; // output 3 4 + 3 / 2 *
System.out.println(ConvertToPostfix(result));
This is the output that I am getting
( 3 4 ) 3 / 2 * +

Evaluating Polish Notation in Java with 2 stacks

I am writing an evaluation code for polish notation. When I overcome ClassCastException I get EmptyStack and when I solve Emptystack I get ClassCast I'm in a loop.
Here is how I wanted to evaluate the Polish notation:
First I get a string from the user then put it into a stack. For evaluating I use a second stack. Why?
Because:
An example string: "* + * + 1 2 + 3 4 5 6" First operation here is to add up 3 and 4 but what I'm gonna do with 5 and 6? I put them in another stack. Let's say stack2. I start popping until I found an operator, in this condition I pushed 6 5 4 3 into stack2 and found a plus operator. Then I pop 2 numbers which I pushed to stack2 (the top 2 numbers are 3 and 4), add them up, and push them to stack again.
I should evaluate but seems like I am missing a point or this wasn't a good idea at first.
Here is my code:
public class Main {
public static void stack(String srt){ // this function puts the string in srt stack
String arr[] = srt.split(" "); // I am recognizing if there is a 2 or more digit number
int size= arr.length; // with receiving prefix with " " btw every number and operator
Stack stack= new Stack();
for (String s : arr) {
// System.out.println(s);
stack.push(s);
}
// for (int i = 0; i < size; i++) {
// System.out.println(stack.pop()); // I checked to see if any
// problems first now I dont start this
// }
evaluate(stack); // then calls the evaluate function
}
public static void evaluate(Stack stack){
Stack stack2= new Stack();
stack2.push(stack.pop());// cuz of there cant be an operator there I pop first 2 number
stack2.push(stack.pop());
for (int i = 0; i < (stack.capacity()*2); i++) { // I had a hard time calculating how many times
// I should cycle through this for and leave it 2 times as stack capacity
if(stack.peek().toString().equals("*") || stack.peek().toString().equals("-") || stack.peek().toString().equals("/") || stack.peek().toString().equals("+")){
System.out.println("Checkpoint1");
// System.out.println(stack2.peek());
int s2= Integer.parseInt((String) stack2.pop());
int s1= Integer.parseInt((String) stack2.pop());
double s3;
String c = (String) stack.pop();
switch (c) {
case "+":
s3=s1+s2;
stack2.push(s3);
case "-":
s3=s1-s2;
stack2.push(s3);
case "*":
s3=s1*s2;
stack2.push(s3);
case "/":
s3=s1/s2;
stack2.push(s3);
}
}else{
System.out.println("Checkpoint 2");
stack2.push(Integer.parseInt((String) stack.pop()));
// System.out.println(stack.peek());
}
}
// System.out.println(stack.peek());
// System.out.println(stack2.peek());
}
public static void main(String[] args) {
String examplestr ="* + * + 1 2 + 3 4 5 6";
stack(examplestr);
}
}
Thank you for your help!!!
So turns out the switch-case doesn't operate correctly because I forgot a fundamental part "break". For EmptyStackException, I made a try-catch and put them inside so when it returns empty stack I know evaluation is done and print the result. BUT I still don't know how to deal with these little problems. It feels like I did not solve them properly. Gotta work more. Thanks.
Edit: I made some more adjustments and this is my final working code. I couldn't detect an error in the results yet.
Here is the working code;
import java.util.EmptyStackException;
import java.util.Stack;
public class Main2 {
public static void stack(String srt) {
String arr[] = srt.split(" ");
int size = arr.length;
Stack stack = new Stack();
for (int i = 0; i < size; i++) {
if (arr[i].toString().equals("*") || arr[i].toString().equals("-") || arr[i].toString().equals("/") || arr[i].toString().equals("+"))
stack.push(arr[i]);
else
stack.push(Double.parseDouble(arr[i]));
}
// for (int i = 0; i < size; i++) {
// System.out.println(stack.pop());
// }
evaluate(stack);
}
public static void evaluate(Stack stack) {
Stack stack1 = new Stack();
stack1.push(stack.pop());
stack1.push(stack.pop());
for (int i = 0; i < stack1.capacity(); i++) {
try {
if (stack.peek().toString().equals("*") || stack.peek().toString().equals("-") || stack.peek().toString().equals("/") || stack.peek().toString().equals("+")) {
// System.out.println("Checkpoint1");
double s1 = (double) stack1.pop();
double s2 = (double) stack1.pop();
double s3;
String operator = String.valueOf(stack.pop());
switch (operator) {
case "+":
s3 = s1 + s2;
stack1.push(s3);
break;
case "-":
s3 = s1 - s2;
stack1.push(s3);
break;
case "*":
s3 = s1 * s2;
stack1.push(s3);
break;
case "/":
s3 = s1 / s2;
stack1.push(s3);
break;
}
} else {
// System.out.println("Checkpoint 2");
stack1.push(Double.parseDouble(String.valueOf(stack.pop())));
}
} catch (EmptyStackException e) {
System.out.println("Notasyonun sonucu: " + stack1.peek());
}
}
}
public static void main(String[] args) {
String notasyon = scanner.nextLine();
stack(notasyon);
}
}

Shortest Palindrome with recursive solution issue

Debugging the following problem (a recursive solution) and confused what is the logical meaning of the for loop. If anyone have any insights, appreciated for sharing.
Given a string S, you are allowed to convert it to a palindrome by adding characters in front of it. Find and return the shortest palindrome you can find by performing this transformation.
For example:
Given "aacecaaa", return "aaacecaaa".
Given "abcd", return "dcbabcd".
int j = 0;
for (int i = s.length() - 1; i >= 0; i--) {
if (s.charAt(i) == s.charAt(j)) { j += 1; }
}
if (j == s.length()) { return s; }
String suffix = s.substring(j);
return new StringBuffer(suffix).reverse().toString() + shortestPalindrome(s.substring(0, j)) + suffix;
KMP based solution,
public class Solution {
public String shortestPalindrome(String s) {
String p = new StringBuffer(s).reverse().toString();
char pp[] = p.toCharArray();
char ss[] = s.toCharArray();
int m = ss.length;
if (m == 0) return "";
// trying to find the greatest overlap of pp[] and ss[]
// using the buildLPS() method of KMP
int lps[] = buildLPS(ss);
int i=0;// points to pp[]
int len = 0; //points to ss[]
while(i<m) {
if (pp[i] == ss[len]) {
i++;
len++;
if (i == m)
break;
} else {
if (len == 0) {
i++;
} else {
len = lps[len-1];
}
}
}
// after the loop, len is the overlap of the suffix of pp and prefix of ss
return new String(pp) + s.substring(len, m);
}
int [] buildLPS(char ss[]) {
int m = ss.length;
int lps[] = new int[m];
int len = 0;
int i = 1;
lps[0] = 0;
while(i < m) {
if (ss[i] == ss[len]) {
len++;
lps[i] = len;
i++;
} else {
if (len == 0) {
i++;
} else {
len = lps[len-1];
}
}
}
return lps;
}
}
thanks in advance,
Lin
My original comment was incorrect - as you've pointed out, in addition to using j'to check if s is a complete Palindrome, j is also used to find (intelligently guess?) the index around which to wrap + reverse the trailing characters from the longest palindrome which might exist at the beginning of the string. My understanding of the algorithm is as follows:
e.g. aacecaaa gives j = 7, resulting in
`aacecaaa` is `aacecaa` (palindrome) + `a` (suffix)
so the shortest palindrome appending to the start is:
`a` (suffix) + `aacecaa` + `a` (suffix)
Where the suffix consists of more than one character it must be reversed:
`aacecaaab` is `aacecaa` (palindrome) + `ab` (suffix)
So the solution in this case would be:
`ba` + `aacecaa` + `ab` (suffix)
In the worst case scenario j = 1 (since a will match when i=0 and j=0), e.g. abcd has no palindrome sequence in it, so the best which can be done is to wrap around the first character
dcb + a + bcd
To be honest, I'm not 100% confident that the algorithm you are debugging will work correctly in all cases but can't seem to find an a failed test case. The algorithm is certainly not intuitive.
Edit
I believe the shortest Palindrome can be derived deterministically, without the need for recursion at all - it seems that in the algorithm you are debugging, the recursion masks a side effect in the value of j. In my opinion, here's a way to determine j in a more intuitive manner:
private static String shortestPalindrome(String s) {
int j = s.length();
while (!isPalindrome(s.substring(0, j))) {
j--;
}
String suffix = s.substring(j);
// Similar to OP's original code, excluding the recursion.
return new StringBuilder(suffix).reverse()
.append(s.substring(0, j))
.append(suffix)
.toString();
}
I've pasted some test cases with an implementation of isPalindrome on Ideone here
public String shortestPalindrome(String s) {
String returnString ="";
int h = s.length()-1;
if(checkPalindrome(s))
{
return s;
}
while(h>=0)
{
returnString =returnString + s.charAt(h);
if(checkPalindrome(returnString+s))
{
return returnString+s;
}
h--;
}
return returnString+s;
}
public boolean checkPalindrome(String s)
{
int midpoint = s.length()/2;
// If the string length is odd, we do not need to check the central character
// as it is common to both
return (new StringBuilder(s.substring(0, midpoint)).reverse().toString()
.equals(s.substring(s.length() - midpoint)));
}

Stack problem java. Postfix Evaluation

Hey Guys I'm having a problem when I run my program. In the PostfixEvaluate() Method is where it takes in a string and solves the postfix problem and returns it. Well when I go to run it, I'm getting a bunch of random numbers(some repeated), I'm going crazy because I don't know what else to try and I've spent more time on this than it should normally take.
Heres the PostfixEvaluate Method:
public int PostfixEvaluate(String e){
//String Operator = "";
int number1;
int number2;
int result=0;
char c;
//number1 = 0;
//number2 = 0;
for(int j = 0; j < e.length(); j++){
c = e.charAt(j);
if (c != '+'&& c!= '*' && c!= '-' && c!= '/') {
//if (c == Integer.parseInt(e)) {
s.push(c);
}
else {
number1 = s.pop();
number2 = s.pop();
switch(c) {
case '+':
result = number1 + number2;
break;
case '-':
result = number1 - number2;
break;
case '*':
result = number1 * number2;
break;
case '/':
result = number1 / number2;
break;
} s.push(result);
}
System.out.println(result);
}
return s.pop();
}
public static void main(String[] args) {
Stacked st = new Stacked(100);
String y = new String("(z * j)/(b * 8) ^2");
String x = new String("2 3 + 9 *");
TestingClass clas = new TestingClass(st);
clas.test(y);
clas.PostfixEvaluate(x);
}
}
This is the Stack Class:
public class Stacked {
int top;
char stack[];
int maxLen;
public Stacked(int max) {
top = -1;
maxLen = max;
stack = new char[maxLen];
}
public void push(int result) {
top++;
stack[top] = (char)result;
}
public int pop() {
int x;
x = stack[top];
//top = top - 1;
top--;
return x;
}
public boolean isStackEmpty() {
if(top == -1) {
System.out.println("Stack is empty " + "Equation Good");
return true;
}
else
System.out.println("Equation is No good");
return false;
}
public void reset() {
top = -1;
}
public void showStack() {
System.out.println(" ");
System.out.println("Stack Contents...");
for(int j = top; j > -1; j--){
System.out.println(stack[j]);
}
System.out.println(" ");
}
public void showStack0toTop() {
System.out.println(" ");
System.out.println("Stack Contents...");
for(int j=0; j>=top; j++){
System.out.println(stack[j]);
}
System.out.println(" ");
}
}
It looks to me like you aren't handling spaces at all.
This means that when you put in a space, it is implicitly converting the character space to the ascii value of it (32) when it pops it off the stack during an operation. Also, it looks like you are assuming that all numbers/results will be single digit, and casting from char to int, which is not what you want to do, since that will convert the char to the ascii value of the char, ' ' -> 32, '3' -> 51, etc.
If I were you, I would do this for your loop in PostfixEvaluate:
while(!e.equals("")){
string c;
int space = e.indexOf(' ');
if(space!=-1){
c = e.substring(0,space);
e = e.substring(space+2);
} else{
c = e;
e = "";
}
if (!c.equals("+")&& !c.equal("*") && !c.equals("-") && !c.equals("/")) {
//...
}
and change your stack to hold strings or ints.
The problem is that you are pushing char onto a stack as an int, so you are unintentionally working with the ascii representations of numbers, which is not the actual value of the number.
Instead of this complicated character walking, tokenize the input string using String.split(). Example:
String[] tokens = e.split(" ");
for(String token:tokens){
if (!"+".equals(token) && !"*".equals(token) && !"-".equals(token) && !"/".equals(token)) {
s.push(Integer.parseInt(token));
} else {
....
}
}
You need to split the string into tokens first:
/* Splits the expression up into several Strings,
* all of which are either a number or and operator,
* none of which have spaces in them. */
String [] expressionAsTokens = e.split(" ");
Then you need to make sure you compare Strings, not chars:
//compare strings instead of chars
String token = expressionAsTokens[j];
if (!"+".equals(token) && !"*".equals(token) && !"-".equals(token) && !"/".equals(token)) {
s.push(Integer.parseInt(token));
} else {
//same code as you had before
}
Also, is there any reason you are storing everything as a char array in your Stacked class? Your pop() method returns and integer, yet everything is stored as a char.
For this application, everything should be stored as an integer:
public class Stacked {
int stack[]; // array is of type integer
int top;
int maxLen;
// constructor
public void push() {/*...*/}
public int pop() {/*...*/} //pop returns an int as before
//...
}
One final note: Be careful what order you add and subtract the numbers in. I don't remember if postfix operands are evaluated left first or right first, but make sure you get them in the right order. As you have it now, 2 3 - 4 * would evaluate as 4 * (3 - 2) and I think it should be (2 - 3) * 4. This won't matter with adding and multiplying, but it will with subtracting and dividing.

Categories