From 3eebb597e8abd4333e7f72b5ce19820106d5345f Mon Sep 17 00:00:00 2001 From: shivani9-codes <72536686+shivani9-codes@users.noreply.github.com> Date: Thu, 8 Oct 2020 09:02:30 +0530 Subject: [PATCH] Create Balanced_Brackets.java --- Balanced_Brackets.java | 47 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 Balanced_Brackets.java diff --git a/Balanced_Brackets.java b/Balanced_Brackets.java new file mode 100644 index 0000000..141cb2e --- /dev/null +++ b/Balanced_Brackets.java @@ -0,0 +1,47 @@ +import java.io.*; +import java.util.*; + +public class Main { + + public static void main(String[] args) throws Exception { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + String str = br.readLine(); + + Stack st = new Stack<>(); + for (int i = 0; i < str.length(); i++) { + char ch = str.charAt(i); + if (ch == '(' || ch == '{' || ch == '[') { + st.push(ch); + } else if (ch == ')') { + if (st.size() == 0 || st.peek() != '(') { + System.out.println(false); + return; + } else { + st.pop(); + } + } else if (ch == '}') { + if (st.size() == 0 || st.peek() != '{') { + System.out.println(false); + return; + } else { + st.pop(); + } + } else if (ch == ']') { + if (st.size() == 0 || st.peek() != '[') { + System.out.println(false); + return; + } else { + st.pop(); + } + } else { + // nothing + } + } + + if (st.size() == 0) { + System.out.println(true); + } else { + System.out.println(false); + } + } +}