Created
July 8, 2016 15:39
-
-
Save tiagopereira17/8d8738160fe17531ce278c00066b6f7b to your computer and use it in GitHub Desktop.
Determine whether a given string of parentheses is properly nested.
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
package stacksandqueues; | |
import java.util.Stack; | |
public class Brackets { | |
public int solution(String S) { | |
if(!S.isEmpty() && S.length() % 2 != 0) { | |
return 0; | |
} | |
Stack<Character> stack = new Stack<>(); | |
char[] toPush = new char[] {'{', '[', '('}; | |
for(char c : S.toCharArray()) { | |
boolean isToPush = false; | |
for(int i = 0; i < toPush.length; i++) { | |
if(toPush[i] == c) { | |
isToPush = true; | |
break; | |
} | |
} | |
if(isToPush) { | |
stack.push(c); | |
} else { | |
if(stack.size() == 0) { | |
return 0; | |
} else if(!areOpositeChar(stack.pop(), c)) { | |
return 0; | |
} | |
} | |
} | |
return stack.size() == 0 ? 1 : 0; | |
} | |
private boolean areOpositeChar(char a, char b) { | |
if(a == '{' && b == '}') { | |
return true; | |
} | |
else if(a == '[' && b == ']') { | |
return true; | |
} else if(a == '(' && b == ')') { | |
return true; | |
} | |
return false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment