boolean Match(char c) {
if (this.type == '[' && c == ']')
return true;
if (this.type == '{' && c == '}')
return true;
if (this.type == '(' && c == ')')
return true;
return false;
}
Stack<Bracket> opening_brackets_stack = new Stack<Bracket>();
for (int position = 0; position < text.length(); ++position)
{
char next = text.charAt(position);
if (next == '(' || next == '[' || next == '{')
{
// Process opening bracket, write your code here
Bracket temp = new Bracket(next,position);
opening_brackets_stack.push(temp);
}
if (next == ')' || next == ']' || next == '}')
{
// Process closing bracket, write your code here
try{
Bracket item = opening_brackets_stack.pop();
if(!item.Match(next))
{ //not match
System.out.println(position+1);
return;
}
}
catch(EmptyStackException e){}
}
}
// Printing answer, write your code here
try{
if(opening_brackets_stack.isEmpty())
{
System.out.println("Success");
}
else {
Bracket item = opening_brackets_stack.pop();
//print position of first unmatched opening bracket
System.out.println(item.position+1);
}
}
catch (EmptyStackException e){}
}
i am getting wrong answer in cases like "}","()}" in which bracket is at last position.
i am supposed to get answer "1","3" respectively for above cases but i am getting "Success".
In all other cases, it works perfectly fine.
What should I do?
With a string like "}", your code tries to pop an opening brace from the stack. But the stack is empty so you get an EmptyStackException, and control is transferred to your exception handler. Which does nothing.
Rather than trying to catch an exception, check to see if the stack is empty. If it is, then you know that you have too many closing braces. Treat it the same way you'd treat a false return from item.Match.
Related
The code is to check weather Duplicate parenthesis exist or not ..
I am getting true for every string. I am unable to find where I am wrong
public class DuplicatePar {
public static void main(String[] args) {
String str = "((a+b)+c)";
System.out.println(dupliPar(str));
}
public static boolean dupliPar(String str){
Stack<Character> s = new Stack<>();
for(int i = 0; i<str.length();i++){
if(str.charAt(i) != ')'){
s.push(str.charAt(i));
}
if(str.charAt(i) == ')' && s.peek() != '('){
while(s.peek() !='('){
s.pop();
}
s.pop();
}
else{
return true;
}
}
return false;
}
}
As written -
if(str.charAt(i) != ')'){
s.push(str.charAt(i));
}
if(str.charAt(i) == ')' && s.peek() != '('){
while(s.peek() !='('){
s.pop();
}
s.pop();
}
else{
return true;
}
Suppose the first char is '(', The condition of the first 'if' is true (it's not a close parenthesis) so we execute the controlled statement (push to stack).
We're now done with that 'if'. The second 'if' has a false condition so we execute the associated 'else' clause and immediately return a 'true' result.
With 'else' added:
if(str.charAt(i) != ')'){
s.push(str.charAt(i));
}
else if(str.charAt(i) == ')' && s.peek() != '('){
while(s.peek() !='('){
s.pop();
}
s.pop();
}
else{
return true;
}
Again, suppose the first char is '(', The condition of the first 'if' is true (it's not a close parenthesis) so we execute the controlled statement (push to stack).
And therefore we do not execute the 'else' clause of the first 'if' statment. The 'else' clause is the entire second if-else construction. Thus we don't return the incorrect result, but keep processing the input string.
That's the solution to the specific problem you reported, but I am not convinced the code works in all cases. Consider the input string ")(" for example.
I have the following code for the solution of Hackerrank.
public static void main(String[] args) {
System.out.println(isBalanced("{(([])[])[]}"));
}
public static String isBalanced(String s) {
Stack<Character> stack = new Stack<>();
stack.push(s.charAt(0));
for (int i = 1; i < s.length(); i++) {
Character c = s.charAt(i);
Character cStack = stack.peek();
if (cStack == '{' && c == '}'
|| cStack == '[' && c == ']'
|| cStack == '(' && c == ')') {
stack.pop();
} else {
stack.push(c);
}
}
if (stack.isEmpty())
return "YES";
return "NO";
}
Although the code seems to working without any problem, it throws the following error on the Hackerrank page. I already test the input in my local IDE as it is {(([])[])[]}, but I am not sure if I need to get the last element (it maybe due to getting it via Character cStack = stack.peek(); and then stack.pop();.
So, could you please have a look at and test this code on Hackerrank page and let me know what is wrong?
Update:
public static String isBalanced(String s) {
Stack<Character> stack = new Stack<>();
stack.push(s.charAt(0));
for (int i = 1; i < s.length(); i++) {
Character c = s.charAt(i);
if (c == '{' || c == '[' || c == '(') {
stack.push(c);
} else if (stack != null) {
Character cStack = stack.peek();
if (cStack == '{' && c == '}'
|| cStack == '[' && c == ']'
|| cStack == '(' && c == ')') {
stack.pop();
}
}
}
if (stack.isEmpty())
return "YES";
return "NO";
}
Before calling stack.peek(), you need to check if the stack is empty or not. Calling pop() or peek() on an empty stack will raise an error.
If the current character is an opening bracket, you don't even need to check the stack top. If it is a closing bracket, then check if the stack is empty or not first. If it is, return false. Otherwise compare the top character and make a decision.
I tried to solve a problem in leetcode and im not able to pass all the test cases. I tried to use stack. Whenever there is an open parenthesis, I push it into the stack and whenever there is a close parentheses, I check and pop if the correct open parenthesis is present on the top of the stack.
I check if the stack is empty in the last
Problem statement:
Given a string containing just
the characters '(', ')', '{', '}', '[' and ']', determine if the
input string is valid.
An input string is valid if:
Open brackets must be closed by the same type of brackets. Open
brackets must be closed in the correct order. Note that an empty
string is also considered valid.
Stack<Character> stk = new Stack<Character>();
boolean check = true;
char temp;
if(s.length() == 1)
{
return false;
}
else if(s.length() == 0)
{
return true;
}
else
{
for(int i = 0 ; i < s.length() ; i++)
{
temp = s.charAt(i);
if(temp == '{' || temp == '(' || temp == '[')
{
stk.push(temp);
}
else if(temp == '}')
{
if(stk.peek() == '{')
{
stk.pop();
}
else
{
check = false;
}
}
else if(temp == ')')
{
if(stk.peek() == '(')
{
stk.pop();
}
else
{
check = false;
}
}
else if(temp == ']')
{
if(stk.peek() == '[')
{
stk.pop();
}
else
{
check = false;
}
}
}
if(check == false && stk.empty() == false)
{
return false;
}
else
{
return true;
}
}
You have simply not taken in consideration cases such as
()), where the stack can be empty when you receive a new closing paranthesis.
Simply add
!stk.isEmpty()&&
before each
stk.peek()
It's generally a good idea when working with vectors, matrix, etc. to verify if the element is within bounds and exists(or give internal reasoning as to why it isn't and why at least a check is necessary).
Also, sometimes you can have stuff such as
(, where the check doesn't meet a mismatching closing paranthesis to turn it into false. However, there is a mismatching opening paranthesis.
So the final part of the code has to be
if(check == false || stk.empty() == false)
instead of &&, I put ||
I've run it on the site and it works :) .
This code works on Leetcode. I've modified it so that instead of setting check to false, it just immediately returns false, since there's no point going through the whole string. It also checks if the stack is empty at each iteration. To avoid failing when the input starts with a closing parentheses, square bracket, or curly brace, it pushes the first character of the string onto the stack at the very start.
I've also improved it a bit by rejecting strings of odd lengths at the very start, which makes it run faster than 98.69% of all submissions to the Leetcode problem.
Stack<Character> stk = new Stack<Character>();
char temp;
int len = s.length();
if(len == 0) {
return true;
} else if (len % 2 == 1) {
return false;
}
stk.push(s.charAt(0));
for(int i = 1; i < len; i++) {
temp = s.charAt(i);
switch (temp) {
case '{':
case '(':
case '[':
stk.push(temp);
break;
case '}':
if (stk.peek() == '{') {
stk.pop();
break;
} else return false;
case ')':
if (stk.peek() == '(') {
stk.pop();
break;
} else return false;
case ']':
if (stk.peek() == '[') {
stk.pop();
break;
} else return false;
}
if (stk.isEmpty()) break;
}
return stk.isEmpty();
I hope you don't mind that I replaced your if-statements with a switch block. It's pretty much the same, but it looks clearer to me, at least. You can always change it back though, it'll work the same.
This seems to work fine:
public boolean isValid(String s) {
int n = s.length();
if (n == 0) return true;
if (n % 2 == 1) return false;
Stack<Character> st = new Stack<>();
for (char c : s.toCharArray()) {
if (c == '{' || c == '[' || c == '(') {
st.push(c);
} else if (st.isEmpty()) { // no opening bracket stored
return false;
} else {
char prev = st.pop();
switch(c) { // matching open and close bracket
case '}': if (prev != '{') return false; else break;
case ']': if (prev != '[') return false; else break;
case ')': if (prev != '(') return false; else break;
}
}
}
return st.isEmpty(); // stack must be empty in the end - all pairs matched
}
I took a half a year off from programming and now Im just refreshing my memory w super basic little interview questions...and Ive been stuck for 2 days on the first one.. Below is my code can someone just hint to me why the program shows no errors but upon compilation does nothing? It should ignore text characters but Im not even there yet
public class bracketCheck {
public static void main(String[] args) {
Stack <Character> s = new <Character> Stack();
Scanner input = new Scanner(System.in);
String buff;
System.out.println("please enter brackets & text");
buff = input.nextLine();
input.close();
int count = 0;
boolean cont = true;
Character stackTop;
Character current = buff.charAt(count);
do {
if(current == ')' || current== '}' || current== ']') {
s.push(current);
count++;
}
else if(current== '(' || current== '{' || current== '[') {
stackTop = s.pop();
cont = match(stackTop, current);
}
}
while(s.isEmpty() == false /*&& cont =true*/);
if(s.isEmpty())
System.out.println("bout time......");
}
private static boolean match(Character top , Character not) {
if(top == ')' && not == '(')
return true;
else if(top == ']' && not == '[')
return true;
else if(top == '}' && not == '{')
return true;
else
return false;
}
}
I saw some issues in your code, this is my fixed version of it
import java.util.Scanner;
import java.util.Stack;
// use Capital letters in the beginning of class names
public class BracketCheck {
public static void main(String[] args) {
Stack<Character> stack = new Stack<>();
Scanner input = new Scanner(System.in);
String buff;
System.out.println("please enter brackets & text");
buff = input.nextLine();
input.close();
// using java8 makes iterating over the characters of a string easier
buff.chars().forEach(current -> {
// if <current> is an opening bracket, push it to stack
if (current == '(' || current == '{' || current == '[') {
stack.push((char) current);
}
// if <current> is a closing bracket, make sure it is matching an opening
// bracket or alert and return
else if (current == ')' || current == '}' || current == ']') {
if (!match(stack, (char) current)) {
System.out.println("no good");
return;
}
}
});
// if, after we finished iterating the string, stack is empty, all opening
// brackets had matching closing brackets
if (stack.isEmpty()) {
System.out.println("bout time......");
}
// otherwise, alert
else {
System.out.println("woah");
}
}
private static boolean match(Stack<Character> stack, Character closer) {
// if stack is empty, the closer has no matching opener
if (stack.isEmpty()) {
return false;
} else {
// get the most recent opener and verify it matches the closer
Character opener = stack.pop();
if (opener == '(' && closer == ')')
return true;
else if (opener == '[' && closer == ']')
return true;
else if (opener == '{' && closer == '}')
return true;
else
return false;
}
}
}
I found a problem and i tried my logic but i failed to get to the solution.
This is the problem i am trying to solve in java.
For every opening brace (i.e., (, {, or [), there is a matching closing brace (i.e., ), }, or ]) of the same type (i.e., (matches ), { matches }, and [ matches ]). An opening brace must appear before (to the left of) it’s matching closing brace. For example, ]{}[ is not balanced.
No unmatched braces lie between some pair of matched braces. For example, ({[]}) is balanced, but {[}] and [{)] are not balanced.
I want to write java code which would take such a string input of braces and output whether it is balanced or not.
I am not able to apply logic for this kind of code, i tried however it was not even close to expectations. Please provide with some logic. I know this is not a homework completion site but i am stuck on the logic of this problem. a code snippet would be appreciated.
This has nothing to do with java. You need to use a stack to keep track of the order in which you encounter the brackets.
Algorithm-
loop over the input string.
If the current character is an opening bracket, push it in the stack
It it is a closing bracket, pop an element from the stack and if it is not the corresponding opening bracket to the current closing bracket then it is not balanced.
After traversing the string, if there is an opening bracket in the stack then it is not balanced.
Try this.
public static boolean isBalanced(String s) {
Deque<Character> stack = new LinkedList<>();
for (int i = 0; i < s.length(); ++i) {
char c = s.charAt(i);
switch (c) {
case '(': stack.push(')'); break;
case '[': stack.push(']'); break;
case '{': stack.push('}'); break;
case ')': case ']': case '}':
if (stack.isEmpty() || !stack.pop().equals(c))
return false;
break;
}
}
return stack.isEmpty();
}
No switch version:
public static boolean isBalanced(String s) {
Deque<Character> stack = new LinkedList<>();
for (int i = 0; i < s.length(); ++i) {
char c = s.charAt(i);
if (c == '(')
stack.push(')');
else if (c == '[')
stack.push(']');
else if (c == '{')
stack.push('}');
else if (c == ')' || c == ']' || c == '}')
if (stack.isEmpty() || !stack.pop().equals(c))
return false;
}
return stack.isEmpty();
}
Another way to solve this problem.
This can be solved using Stack Datastructure.
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String string = in.next(); //input string -> eg : {{[[(())]]}}
boolean check = Paran(string);
if(check){
System.out.println("YES");
}
else{
System.out.println("NO");
}
}
//function that checks brackets are balanced or not
public static boolean Paran(String string){
//create a stack
Stack<Character> s = new Stack<Character>();
//check if string is empty
//if string is empty then Balanced
if(string.length() == 0){
return true;
}
//if string is not empty, go through each character
for(int i = 0; i< string.length(); i++){
//fetch each character
char current = string.charAt(i);
//check if that character id any of {([
// if yes push on to the stack
if(current == '[' || current == '{' || current == '('){
s.push(current);
}
//check if that character id any of }])
if(current == '}' || current == ']' || current == ')'){
//check stack is empty
//if yes then return false
if(s.isEmpty()){
return false;
}
//else fetch top most item
char pre = s.peek();
if((current == '}' && pre == '{') || (current == ']' && pre == '[') || (current == ')' && pre == '(')){
s.pop();
}
else{
return false;
}
}
}
return s.isEmpty();
}
}
Hope this helps