Code running to slow to pass . Can't figure out why - java

I have to solve this exercise and I am pretty new to coding. The task is:
In this problem, the input to your program is an array of N characters, each of which is either (, ), [ or ], and your program must return true if the parentheses are properly matched, and false if they are not.
The code works and solves all the tests correct, but it is to slow to pass overall and I can't figure out why. What can I do to improve the speed of the code? Thank in advance.
public class Dyck {
public boolean checkParentheses(ArrayList<Character> input) {
Stack<Character> s = new Stack<>();
Stack<Character> s2 = new Stack<>();
for(var c : input){
s.add(0, c);
}
Character c2;
Character c = s.pop();
if (c != ')' && c != ']') {
s2.add(c);
}
var size = s.size();
for (int i = 0; i < size; ++i) {
c = s.pop();
if (c == '[' || c == '(') {
s2.add(c);
}
if (c == ')') {
if (s2.isEmpty()) {
return false;
}
c2 = s2.pop();
if (c2 != '(') {
return false;
}
}
if (c == ']') {
if (s2.isEmpty()) {
return false;
}
c2 = s2.pop();
if (c2 != '[') {
return false;
}
}
}
if (s.isEmpty() && s2.isEmpty()) {
return true;
}
return false;
}

Related

Palindrome Stack

I wrote this method to check to see if a words is a palindrome, but when it is a palindrome it keeps returning false
public boolean isPalindrome(String s){
int i;
int n = s.length();
Stack <Character> stack = new Stack <Character>();
for (i = 0; i < n/2; i++)
stack.push(s.charAt(i));
if (n%2 == 1)
i++;
while(!stack.empty( )) {
char c = stack.pop( );
if (c != s.charAt(i));
return false;
}
return true;
}
I'm not sure why you're not using { } brackets. Try to learn proper Java conventions early.
if (c != s.charAt(i)); // <- this semicolon is your problem
return false;
Is equivalent to:
if (c != s.charAt(i)) {
// Do nothing
}
// Do this no matter what
return false;
Furthermore, the logic on your for-loop may be flawed for similar reasons. Remove your semicolon, and better yet, practice always using brackets:
if (c != s.charAt(i)) {
return false;
}
#jhamon also points out that you never actually increment i in your while loop:
while(!stack.empty( )) {
char c = stack.pop( );
if (c != s.charAt(i)) {
return false;
}
i++;
}

Trying to implement a stack and the bracket matching problem but cannot figure out some semantic errors

I am required to write my own stack using an array which then I have to implement the bracket matching problem.
This is my algorithm: if we're given the string: "(())" it is returning "not balanced" when it should say it is "balanced". If you look over at BracketCheck.java near the end it tests whether the stack is empty where if it is it should return true and say the given string: "(())" is balanced. I am having problems debugging it and the result of the operation is incorrect.
Here is my stack and main class code:
public class Stack {
// instance fields:
private char array[]; // our array
private int topOfStack; // this indicates the value for each position
// overloaded constructor:
public Stack(int size) {
this.array = new char[size]; // here we instantiate a new char type array.
this.topOfStack = -1; // we set the starting position of the topOfStack to -1.
}
// push method:
public void push(char character) {
if(isFull() == true) {
System.out.println("Stack overflow error.");
}
else {
topOfStack++;
array[topOfStack] = character;
}
}
// pop method:
public char pop() {
if(isEmpty() == true) {
//System.out.println("Overflow.");
return '\0';
}
else {
char c = array[topOfStack];
topOfStack--;
return c;
}
}
// top method:
public int top() {
if(isEmpty() == true) {
System.out.println("The stack is empty.");
return 0;
}
else {
return array[topOfStack]; // returns the top element in the stack.
}
}
// size method:
public int size() {
return topOfStack + 1;
}
// isEmpty method:
public boolean isEmpty() {
if(topOfStack == -1) {
return true;
}
else {
return false;
}
}
// isFull method:
public boolean isFull() {
if(topOfStack == array.length -1 ) {
System.out.println("Stack if full.");
return true;
}
else {
return false;
}
}
BracketCheck.java
public class BracketCheck {
public static void main(String args[]) {
String text = "(())";
//boolean check = isBalanced(text);
if(isBalanced(text) == true) {
System.out.println("Balanced.");
}
else {
System.out.println("Not balanced");
}
}
public static boolean isBalanced(String text) {
Stack stack = new Stack(25); // for simplicity our stack is going to be a size of 25.
char[]arr = text.toCharArray(); // convert our string to a set of characters in an array.
// here we are looping through our text
for(int i = 0; i < arr.length; i++) {
if(arr[i] == '{' || arr[i] == '(' || arr[i] == '[') {
stack.push(arr[i]);
}
else if(arr[i] == '}' || arr[i] == ')' || arr[i] == ']') {
if(stack.isEmpty()) {
return false; // if empty then return false.
}
else if((stack.pop() == '(' && arr[i] != ')') || (stack.pop() == '{' && arr[i] != '}') || (stack.pop() == '[' && arr[i] != ']')) {
return false; // here we return false because this tells us that there is a mismatch and not balanced. Also if we did pop out the brace and it was equal
// to it's corresponding closing brace then it will just continue the loop other return false to indicate it is unbalanced.
}
}
}
if(stack.isEmpty()) {
return true; // after looping through the text if the stack turns out to be empty then this shows that there the text is balanced indeed because
}
else {
return false;
}
}
}
In this condition
else if((stack.pop() == '(' && arr[i] != ')') || (stack.pop() == '{' && arr[i] != '}') || (stack.pop() == '[' && arr[i] != ']')) {
You pop 3 times, so you extract 3 different elements from your stack. To fix it, pop once and save popped element in local variable:
if(stack.isEmpty()) {
return false; // if empty then return false.
}
else {
char element = stack.pop();
if((element == '(' && arr[i] != ')') || (element == '{' && arr[i] != '}') || (element == '[' && arr[i] != ']')) {
return false;
}
}

how to check number exists between braces

import java.util.Stack;
import java.util.Scanner;
public class CheckValidLocationofParenthensies {
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter five data");
String input1 = scanner.next();
balancedParenthensies(input1);
}
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);
if(c == '[') {
newvalueforforward(s,']', i);
}
if(c == '{') {
newvalueforforward(s,'}', i);
}
if(c == '(') {
newvalueforforward(s,')', i);
}
} else if(c == ']') {
if(stack.isEmpty() || stack.pop() != '[') {
newvalue(s,'[', i);
return false;
}
} else if(c == ')') {
if(stack.isEmpty() || stack.pop() != '(') {
newvalue(s,'(', i);
return false;
}
} else if(c == '}') {
if(stack.isEmpty() || stack.pop() != '{') {
newvalue(s,'{', i);
return false;
}
}
}
return stack.isEmpty();
}
public static void newvalueforforward(String userval,char value,int decremntval) {
for(int i = 0; i < userval.length(); i++){
StringBuilder newvalue = new StringBuilder(userval);
int location=i;
newvalue.insert(i, value);
boolean valid= checkingnewvalueisValidorNot(newvalue, location);
location=i+1;
if(valid) {
System.out.println(newvalue+" "+""+location);
}
}
}
public static void newvalue(String userval,char value,int decremntval) {
for(int i = decremntval; i >= 0; i--){
StringBuilder newvalue = new StringBuilder(userval);
int location=decremntval - i;
newvalue.insert(decremntval - i, value);
boolean valid= checkingnewvalueisValidorNot(newvalue, location);
if(valid) {
System.out.println(newvalue+" "+""+location);
}
}
}
public static boolean checkingnewvalueisValidorNot(StringBuilder userval,int validpath) {
Stack<Character> stack = new Stack<Character>();
for(int i = 0; i < userval.length(); i++) {
char c = userval.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();
}
}
Above is the code i have written to check whether input string contains all balanced brackets if it is not balanced then get missing bracket and place bracket in all index then again check whether string is balanced or not.
I got valid output but problem is between i bracket there should be a intergers
here is input and outputs
input missing outputs
{[(2+3)*6/10} ] {[](2+3)*6/10} 3 not valid(no numbres btn bracket)
{[(2+3)]*6/10} 8 valid
{[(2+3)*]6/10} 9 not valid(after * no number)
{[(2+3)*6]/10} 10 valid
{[(2+3)*6/]10} 11 not valid( / before bracket)
{[(2+3)*6/1]0} 12 not valid( / btn num bracket)
{[(2+3)*6/10]} 13 valid
i am failing to do proper validation to my output.
Before the bracket there may be:
number
closing bracket
After the bracket there may be:
operator
closing bracket
end of expression
(ignoring any whitespace)

Java Stack Boolean Output Customization?

So what I have is this slightly modified version of a code that's here a hundred times over for Java Stack Balancing.
import java.util.Stack;
public class Main {
public static String testContent = "{(a,b)}";
public static void main(String args[])
{
System.out.println(balancedParentheses(testContent));
}
public static boolean balancedParentheses(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()) return false;
if(stack.pop() != '[') return false;
}else if(c == ')')
{
if(stack.isEmpty()) return false;
if(stack.pop() != '(') return false;
}else if(c == '}')
{
if(stack.isEmpty()) return false;
if(stack.pop() != '{') return false;
}
}
return stack.isEmpty();
}
}
What I'd like to do is customize the output such that it would output something like "balanced" or "imbalanced" instead of true/false. Trying to replace return false; with a System.println containing 'balanced' gives me a whole lot of output lines I didn't want. Been searching around here for about an hour and some change and couldn't quite find the answer I was looking for. Any insight?
You could use something like
System.out.println(balancedParentheses(testContent) ? "balanced" : "imbalanced");
OR if you want a method that returns a String wrap the logic in another method
String isBalanced(String expression) {
return balancedParentheses(expression) ? "balanced" : "imbalanced"
}
and in main()
System.out.println(isBalanced(testContent));
Also you could write the code something like this
public static boolean balancedParentheses(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 == ']' || c == ')' || c == '}') {
if (stack.isEmpty() || !matches(stack.pop(), c))
return false;
}
}
return stack.isEmpty();
}
private static boolean matches(char opening, char closing) {
return opening == '{' && closing == '}' ||
opening == '(' && closing == ')' ||
opening == '[' && closing == ']';
}

How to check String using stack

I have some specific task. We have String like "(()[]<>)" or something familiar with this. A question in my interview qustion was how check either String is correct or incorrect. For example: "()[]<>" - true, "([)" - false, "[(])" - false, "([<>])" - true. Thank you guys very much!
I can' t take what's wrong with my code.
Thank a lot guys!!!
Please help!
import java.util.Stack;
public class Test {
public static void main(String[] args) {
String line = "(<>()[])";
Test test = new Test();
boolean res = test.stringChecker(line);
System.out.println(res);
}
public boolean stringChecker(String line){
boolean result = false;
char letter = '\u0000';
char[] arr = line.toCharArray();
Stack<Character> stack = new Stack();
for (int i = 0; i < arr.length; i++) {
if (arr[i] == '(' || arr[i] == '[' || arr[i] == '<') {
stack.push(arr[i]);
}
if(arr[i] == ')' || arr[i] == ']' || arr[i] == '>'){
if(stack.peek() == arr[i]){
result = true;
stack.pop();
}
}
}
return result;
}
}
(0) You are pushing < ( and { but in your peek you are checking for >, ), and }
(1) You are starting with result false and setting it to true on the first successful match. Instead you should start with result true and set it to false on the first failed match.
(2) You should check that the stack is empty when you have run out of characters.
(3) You should check for the stack being empty before you peek.
(4) You might want to check for characters that are not expected.
In addition to #TheodoreNorvell 's explanation here is how an implementation could look like
public boolean stringChecker(String input) {
boolean result = true;
char[] arr = input.toCharArray();
Stack<Character> stack = new Stack<>();
try {
for (int i = 0; result && i < arr.length; i++) {
if (arr[i] == '(' || arr[i] == '[' || arr[i] == '<') {
stack.push(arr[i]);
} else if(arr[i] == ')') {
Character c = stack.pop();
result = c.equals('(');
} else if(arr[i] == ']') {
Character c = stack.pop();
result = c.equals('[');
} else if(arr[i] == '>') {
Character c = stack.pop();
result = c.equals('<');
} else {
// found some char that is not allowed
// here it is not just ignored,
// it invalidates the input
result = false;
}
}
// when the teher is not more chars in the array
// the stack has to be empty
result = result && stack.isEmpty() ;
} catch(EmptyStackException e) {
// found a closing bracket in the array
// but there is nothing on the stack
result = false;
}
return result;
}
#Test
public void stringChecker() {
Assert.assertTrue(stringChecker("[]"));
Assert.assertTrue(stringChecker("[(<>)]"));
Assert.assertFalse(stringChecker("([<>)]"));
Assert.assertFalse(stringChecker(">"));
// invalid char
Assert.assertFalse(stringChecker("<[]e>"));
// stack is not empty
Assert.assertFalse(stringChecker("("));
}
Note that in such a situation a switch-case statement is more elegant than if-else if-else.

Categories