Skip to content

Instantly share code, notes, and snippets.

@pravatbhusal
Created January 5, 2019 22:34
Show Gist options
  • Save pravatbhusal/0951efdc60e6c7a643b24e76176432b3 to your computer and use it in GitHub Desktop.
Save pravatbhusal/0951efdc60e6c7a643b24e76176432b3 to your computer and use it in GitHub Desktop.
A Java class that returns true or false if parenthesis syntax is valid. This assignment was inspired by a programming interview question I received from a technical interview for a developer internship.
public class ParenthesisSyntax {
// returns if the parenthesis syntax is valid
public static boolean isParanthesSyntaxValid(String paranthesis) {
return isFirstLastValid(paranthesis) && areSequencesValid(paranthesis);
}
// return if the first or last character is invalid syntax
private static boolean isFirstLastValid(String paranthesis) {
final int PARANTHESIS_LENGTH = paranthesis.length();
// return first character as valid '(' and last character as valid if ')'
return paranthesis.charAt(0) == '(' || paranthesis.charAt(PARANTHESIS_LENGTH - 1) == ')';
}
// return if the parenthesis sequences are valid
private static boolean areSequencesValid(String paranthesis) {
final int PARANTHESIS_LENGTH = paranthesis.length();
int open = 0;
int closed = 0;
boolean searchOpen = true;
for(int i = 0; i < PARANTHESIS_LENGTH; i++) {
if(paranthesis.charAt(i) == '(' && searchOpen) {
open++;
} else if(paranthesis.charAt(i) == '(') {
// a parenthesis sequence finished, check parenthesis count
if(open != closed) {
return false;
}
// search for open parenthesis again
searchOpen = true;
open++;
} else if(paranthesis.charAt(i) == ')') {
closed++;
searchOpen = false;
}
}
// fence-post solution
return closed == open;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment