From 6522012065712fb0ece31bff9ff10b38a83b10e1 Mon Sep 17 00:00:00 2001 From: Michael Hunteman Date: Thu, 22 Sep 2022 10:14:04 -0500 Subject: Initial commit --- Parentheses.java | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 Parentheses.java (limited to 'Parentheses.java') diff --git a/Parentheses.java b/Parentheses.java new file mode 100644 index 0000000..b1a1b82 --- /dev/null +++ b/Parentheses.java @@ -0,0 +1,26 @@ +import java.lang.*; +import java.util.*; + +class Parentheses { + public static boolean isValid(String s) { + HashMap map = new HashMap(); + map.put(')','('); + map.put(']','['); + map.put('}','{'); + Stack stack = new Stack(); + char[] arr = s.toCharArray(); + stack.push(arr[0]); + for (int i = 1; i < arr.length; i++) { + if (arr[i] == '(' || arr[i] == '[' || arr[i] == '{') + stack.push(arr[i]); + else if (map.get(arr[i]) == stack.peek()) + stack.pop(); + } + return stack.isEmpty(); + } + + public static void main(String[] args) { + String s = ")("; + System.out.println(isValid(s)); + } +} -- cgit v1.2.3