Created
June 17, 2014 17:08
-
-
Save rox163/2d2b1e5663fc358dc76c to your computer and use it in GitHub Desktop.
This file contains hidden or 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 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