From 549531f7ed10a6d9703b5a5b60bd1f0e3af28aec Mon Sep 17 00:00:00 2001 From: Priyanshu Saluja Date: Tue, 5 Oct 2021 01:12:25 +0530 Subject: [PATCH] Added Balanced Parenthesis in Java --- balancedparenthesis.java | 48 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 balancedparenthesis.java diff --git a/balancedparenthesis.java b/balancedparenthesis.java new file mode 100644 index 0000000..97023ab --- /dev/null +++ b/balancedparenthesis.java @@ -0,0 +1,48 @@ +import java.util.*; + +public class Main +{ + + public static boolean balanaced(String s) { + Stack stack = new Stack(); + 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 "); + //} +} \ No newline at end of file