Created
August 23, 2020 11:16
-
-
Save Audhil/a0c0366490589e6058f78921be807efb to your computer and use it in GitHub Desktop.
check is it given string is balanced parenthesis?!
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static void main(String[] args) { | |
HashMap<Character, Character> map = new HashMap<>(); | |
map.put('(', ')'); | |
map.put('{', '}'); | |
map.put('[', ']'); | |
String ipString = "{[}]"; | |
System.out.println(isBalancedParenthesis(map, ipString)); | |
} | |
private static boolean isBalancedParenthesis(Map<Character, Character> map, | |
String inputString) { | |
Stack<Character> stack = new Stack<>(); | |
for (char c : inputString.toCharArray()) { | |
if (map.containsKey(c)) | |
stack.push(c); | |
else if (map.containsValue(c)) { | |
if (!stack.isEmpty() && map.get(stack.peek()) == c) | |
stack.pop(); | |
else | |
return false; | |
} | |
} | |
return stack.isEmpty(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment