Last active
August 29, 2015 14:12
-
-
Save dmnugent80/c1425229d546ad39088a to your computer and use it in GitHub Desktop.
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
/* Balanced delimiter problem | |
Opening: (, [, { | |
Closing: ), ], } | |
Valid: {}()[] | |
([{}]) | |
Invalid: ([)] | |
*/ | |
public boolean isValidDelimiter( String str ){ | |
Stack<Character> stackDels= new Stack<Character>(); | |
HashMap<Character, Character> mapDels = new HashMap<Character, Character>(); | |
mapDels.put(')', '('); | |
mapDels.put(']', '['); | |
mapDels.put('}', '{'); | |
for (int i=0; i < str.size(); i++){ | |
//push opening delimiters to stack | |
if (mapDels.containsValue(str.charAt(i))) | |
stackDels.push(str.charAt(i)); | |
} | |
else{ | |
//If stack is empty, we have a closing delimiter with no opening delimiter, so input is invalid | |
if (stackDels.empty()); | |
return false; | |
//for closing delimiters, ensure top of stack contains the corresponding opening delimiter | |
if (mapDels.get(str.charAt(i)) == stackDels.peek()){ | |
stackDels.pop(); | |
} | |
else{ | |
return false; | |
} | |
} | |
//if stack is not empty, we have one or more opening delimiters with no corresponding closing delimiter | |
return (stackDels.empty()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment