Skip to content

Instantly share code, notes, and snippets.

@mchernyavskaya
Created February 19, 2017 12:17
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 mchernyavskaya/f31c77d65e506a114472fde68f26ff8e to your computer and use it in GitHub Desktop.
Save mchernyavskaya/f31c77d65e506a114472fde68f26ff8e to your computer and use it in GitHub Desktop.
import java.util.*;
public class Groups{
private static final List<Character> OPEN = Arrays.asList('(', '{', '[');
private static final List<Character> CLOSE = Arrays.asList(')', '}', ']');
public static boolean groupCheck(String s){
if (s == null || s.length() == 0) {
return true;
}
Stack<Character> stack = new Stack<>();
for (int i = 0; i < s.length(); i++) {
char current = s.charAt(i);
if (isOpen(current)) {
stack.push(current);
} else {
if (stack.isEmpty()) {
return false;
}
char prev = stack.peek();
if (isMatch(prev, current)) {
stack.pop();
}
}
}
return stack.isEmpty();
}
private static boolean isOpen(char c) {
return OPEN.contains(c);
}
private static boolean isClose(char c) {
return CLOSE.contains(c);
}
private static boolean isMatch(char prev, char next) {
return isOpen(prev) && (OPEN.indexOf(prev) == CLOSE.indexOf(next));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment