Created
September 28, 2014 18:26
-
-
Save antoniobg/64c124c3a5018cb31538 to your computer and use it in GitHub Desktop.
ParenthesisChecker
This file contains hidden or 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
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