Skip to content

Instantly share code, notes, and snippets.

@osgix
Created May 10, 2017 08:47
Show Gist options
  • Save osgix/6e2f3826810468d11d9154b066d5a145 to your computer and use it in GitHub Desktop.
Save osgix/6e2f3826810468d11d9154b066d5a145 to your computer and use it in GitHub Desktop.
Check paranthesis in given string whether they are closed appropriately or not.
import java.util.Stack;
public class CheckParanthesis {
public static void main(String[] args) {
System.out.println(isValidParanthesis("a(bcd)d"));
System.out.println(isValidParanthesis("(kjds(hfkj)sdhf"));
System.out.println(isValidParanthesis("(sfdsf)(fsfsf "));
System.out.println(isValidParanthesis("{[]}()"));
System.out.println(isValidParanthesis("{[}]"));
}
private static boolean isValidParanthesis(String input) {
if (input.isEmpty()) {
return true;
}
int length = input.length();
Stack<Character> stack = new Stack<>();
for (int i = 0; i < length; i++) {
char next = input.charAt(i);
if (next == '(' || next == '{' || next == '[') {
stack.push(Character.valueOf(next));
} // || next == '}' || next == ']'
else if (next == ')') {
Character last = stack.pop();
if (last.charValue() != '(') {
return false;
}
}
else if (next == '}') {
Character last = stack.pop();
if (last.charValue() != '{') {
return false;
}
}
else if (next == ']') {
Character last = stack.pop();
if (last.charValue() != '[') {
return false;
}
}
// otherwise dismiss the character
}
return stack.isEmpty() ? true : false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment