Skip to content

Instantly share code, notes, and snippets.

@Audhil
Created August 23, 2020 11:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Audhil/a0c0366490589e6058f78921be807efb to your computer and use it in GitHub Desktop.
Save Audhil/a0c0366490589e6058f78921be807efb to your computer and use it in GitHub Desktop.
check is it given string is balanced parenthesis?!
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