Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added Balanced Parenthesis in Java #26

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 48 additions & 0 deletions balancedparenthesis.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import java.util.*;

public class Main
{

public static boolean balanaced(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() || 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();
}

public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while(sc.hasNext()) {
String input = sc.next();
System.out.println(balanaced(input));
}
}

//or

//public static void main(String[] args)
//{
// String s="({[]})";

// if (isBalanced(s))
// System.out.println("Balanced ");
//else
// System.out.println("Not Balanced ");
//}
}