Skip to content

Instantly share code, notes, and snippets.

@antoniobg
Created September 28, 2014 18:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save antoniobg/64c124c3a5018cb31538 to your computer and use it in GitHub Desktop.
Save antoniobg/64c124c3a5018cb31538 to your computer and use it in GitHub Desktop.
ParenthesisChecker
public class ParenthesisChecker {
public void isValid(String s) throws Exception {
// Adds one for each open parenthesis, and subtracts one for each closed parenthesis
// In the end, count must be 0 and count can't be lower than 0 at any time.
int count = 0;
for(int i = 0; i < s.length(); i++) {
char current = s.charAt(i);
if (current == '(')
count++;
else if (current == ')')
count--;
if (count < 0)
break;
}
if (count != 0)
throw new Exception("Exception Mismatched Parenthesis");
System.out.println("Successful");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment