Skip to content

Instantly share code, notes, and snippets.

@dmnugent80
Last active August 29, 2015 14:12
Show Gist options
  • Save dmnugent80/c1425229d546ad39088a to your computer and use it in GitHub Desktop.
Save dmnugent80/c1425229d546ad39088a to your computer and use it in GitHub Desktop.
/* 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