Skip to content

Instantly share code, notes, and snippets.

@Telewa
Last active April 17, 2020 19:45
Show Gist options
  • Select an option

  • Save Telewa/7c76144e9466f6f35d4690bf802d0791 to your computer and use it in GitHub Desktop.

Select an option

Save Telewa/7c76144e9466f6f35d4690bf802d0791 to your computer and use it in GitHub Desktop.
import java.util.*;
/**
* Check if a string has balanced braces, brackets and curly brackets
*
* Key Note: Use a stack data structure. Only pop when the stack top == current item in the string, else
* push
*
* @author emmanuel
*/
class Solution {
public static void main(String[] argh) {
String input = "{}";
System.out.println(balanced(input));
}
public static boolean balanced(String input){
HashMap<Character, Character> mapping = new HashMap<>();
mapping.put('{', '}');
mapping.put('(', ')');
mapping.put('[', ']');
// allowed characters
ArrayList<Character> characters = new ArrayList<>();
characters.add('{');
characters.add('[');
characters.add('(');
characters.add(')');
characters.add(']');
characters.add('}');
Stack<Character> stack = new Stack<>();
for (int i = 0; i < input.length(); i++) {
char current_type = input.charAt(i);
if (characters.contains(current_type)) {
if (stack.empty()) {
stack.push(current_type);
} else if (mapping.get(stack.peek()) != null && current_type == mapping.get(stack.peek())) {
stack.pop();
} else {
stack.push(current_type);
}
}
}
return stack.empty();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment