Skip to content

Instantly share code, notes, and snippets.

@rox163
Created June 17, 2014 17:08
Show Gist options
  • Select an option

  • Save rox163/2d2b1e5663fc358dc76c to your computer and use it in GitHub Desktop.

Select an option

Save rox163/2d2b1e5663fc358dc76c to your computer and use it in GitHub Desktop.
public static boolean balance(String str) {
HashMap<String, String> delimMap = new HashMap<String, String>();
delimMap.put("{", "}");
delimMap.put("(", ")");
Stack<Character> delimStack = new Stack<Character>();
for (int i = 0; i < str.length(); i++) {
if (delimMap.containsKey(String.valueOf(str.charAt(i)))) {
delimStack.push(str.charAt(i));
} else {
if (!delimStack.empty()) {
String lastOpen = delimStack.pop().toString();
if (!delimMap.get(lastOpen).equals(String.valueOf(str.charAt(i)))) {
return false;
}
} else {
return false;
}
}
}
if (!delimStack.empty()) {
return false;
}
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment