Verify whether the next char is the same as first char - java

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

Related

Java Stack error after getting last element via pop method

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.

Is there a better way to write a java code for detecting valid parentheses in a String?

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
}

Getting wrong output in a test case in Chech brackets in code

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.

Character stack to check matching brackets no errors but also doesnt appear to do anything

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;
}
}
}

Undefined char in output of bracket-matching program using custom stack

My Java Program is below. It's my training exercise. The one implements stack stucture for special type of string parsing(string with delimiter).
This delimiter-matching program works by reading characters from the string one at
a time and placing opening delimiters when it finds them, on a stack. When it reads
a closing delimiter from the input, it pops the opening delimiter from the top of the
stack and attempts to match it with the closing delimiter. If they’re not the same
type (there’s an opening brace but a closing parenthesis, for example), an error
occurs. Also, if there is no opening delimiter on the stack to match a closing one, or
if a delimiter has not been matched, an error occurs. A delimiter that hasn’t been
matched is discovered because it remains on the stack after all the characters in the
string have been read.
I use Eclipse. My output is here:
Please enter String:
{}
ch0 = {
ch1 = }
chLabel1 = **UNDEFINED CHAR(SQUARE WITH QUESTION MARK INSIDE IT)**
Error at }**
Could you explain value of chLabel?
As I understand operator "|" (here, cause two operands have boolean type) - is "lazy", shortcut version of "||" operator. I've tested the program after substitution "|" for "||"-result is the same.
public class MyStack {
private int top=0;
private int maxSize=0;
private char[] charArray=null;
public MyStack(int size){
maxSize=size;
top=0;
charArray=new char[maxSize];
}
public void push(char ch){
charArray[top++]=ch;
}
public char pop(){
return charArray[top--];
}
public boolean isEmpty(){
if(top==0)
return true;
else return false;
}
public boolean isFull(){
if(top==(maxSize-1))
return true;
else return false;
}
}
class StringParse {
private String stringForParsing = null;
public StringParse(String string) {
this.stringForParsing = string;
}
public void parser() {
char[] chArr = stringForParsing.toCharArray();
MyStack mySt = new MyStack(chArr.length);
for (int i = 0; i < chArr.length; i++) {
char ch = chArr[i];
switch (ch) {
case '{':
case '(':
case '[':
mySt.push(ch);
System.out.println("ch" + i + " = " + ch);
break;
case '}':
case ')':
case ']':
if (mySt.isEmpty())
System.out.println("Error at" + ch);
else {
char chLabel = mySt.pop();
System.out.println("ch" + i + " = " + ch);
System.out.println("chLabel" + i + " = " + chLabel);
if ((chLabel == '{') && (ch == '}') | (chLabel == '(') && (ch == ')') | (chLabel == '[') && (ch == ']'))
break;
else {
System.out.println("Error at " + ch);
break;
} // end of second else
} //end of first else
default:
break;
} //end of switch
} //end of parser method
}
} //end of class
class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System. in ));
System.out.println("Please enter String:");
String s = br.readLine();
StringParse strP = new StringParse(s);
strP.parser();
}
}
There are two problems:
There's an error with the pop function.
Consider doing one push and then one pop:
top = 0
push
insert at position 0
set top to 1
pop
get position 1 (not set yet!)
set top to 0
You need to use pre-decrement instead of post-decrement, so charArray[top--] should be charArray[--top].
With this change I get chLabel1 = {.
Reiterating what I said in the comments...
| has higher precendence than &&(as opposed to || which has lower precedence) (see this)‌​,
thus a && b | c && d is the same as a && (b | c) && d,
as opposed to a && b || c && d which would be (a && b) || (c && d).
When changing the |'s to ||'s, I no longer get Error at }.
There may be a problem with your MyStack class
Using java.util.Stack gives me no error, just a "chLabel1 = {"
Error at } can be resolved by following Dukeling's advice and using || instead of |:
(chLabel == '{') && (ch == '}') || (chLabel == '(') && (ch == ')') || (chLabel == '[') && (ch == ']')
So, it looks like your code in MyStack.pop() doesn't return a valid char. I'll need to see your MyStack code to help further.

Categories