Created
December 13, 2018 08:20
-
-
Save avraamisvi/33e5b5f35f9dd432d86386b8c95a3442 to your computer and use it in GitHub Desktop.
Checking Groups
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
import java.util.Deque; | |
import java.util.HashMap; | |
import java.util.LinkedList; | |
import java.util.Objects; | |
public class Groups{ | |
static class Group { | |
final Character close; | |
final Character open; | |
public Group(Character open, Character close) { | |
this.open = open; | |
this.close = close; | |
} | |
boolean isOpen(Character chara) { | |
return open.equals(chara); | |
} | |
boolean isClose(Character chara) { | |
return close.equals(chara); | |
} | |
@Override | |
public boolean equals(Object o) { | |
if (this == o) return true; | |
if (o == null || getClass() != o.getClass()) return false; | |
Group group = (Group) o; | |
return Objects.equals(close, group.close) && | |
Objects.equals(open, group.open); | |
} | |
@Override | |
public int hashCode() { | |
return Objects.hash(close, open); | |
} | |
} | |
static HashMap<Character, Group> groups; | |
static { | |
createTypes(); | |
} | |
private static void createTypes() { | |
groups = new HashMap<>(); | |
String groups = "(){}[]"; | |
for(int i = 0; i < groups.length(); i=i+2) { | |
Group group = new Group(groups.charAt(i), groups.charAt(i+1)); | |
Groups.groups.put(group.open, group); | |
Groups.groups.put(group.close, group); | |
} | |
} | |
public static boolean groupCheck(String s){ | |
Deque<Character> stack = new LinkedList<>(); | |
if(s == null || s.isEmpty()) | |
return true; | |
if(isClose(s.charAt(0))) | |
return false; | |
if(isOpen(s.charAt(s.length()-1))) | |
return false; | |
for(int i = 0; i < s.length(); i++) { | |
Character current = s.charAt(i); | |
Group currentGroup = groups.get(current); | |
if(currentGroup.isClose(current)) { | |
if(stack.isEmpty()) { | |
return false; | |
} | |
Character first = stack.getFirst(); | |
Group firstGroup = groups.get(first); | |
if(!currentGroup.equals(firstGroup)) { | |
return false; | |
} | |
stack.pop(); | |
continue; | |
} | |
stack.addFirst(current); | |
} | |
return stack.isEmpty(); | |
} | |
private static boolean isOpen(char charAt) { | |
return groups.get(charAt).isOpen(charAt); | |
} | |
private static boolean isClose(char charAt) { | |
return groups.get(charAt).isClose(charAt); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment