Skip to content

Instantly share code, notes, and snippets.

@khoatle
Created April 12, 2013 05:47
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 khoatle/5369724 to your computer and use it in GitHub Desktop.
Save khoatle/5369724 to your computer and use it in GitHub Desktop.
import java.util.*;
public class AlienLanguage {
private static class Token {
Set<Character> validChars = new HashSet<Character>();
public Token(String string) {
for(int i = 0; i < string.length(); i++) {
validChars.add(string.charAt(i));
}
}
public boolean contains(char c) {
return validChars.contains(c);
}
public String toString() {
String returnStr = "";
for(Character c : validChars) {
returnStr += c;
}
return returnStr;
}
}
public static void main(String args[]) {
// List<Token> tokens = alienSplit("(abc)b(jkc)");
// for(Token token : tokens) {
// System.out.println(token);
// }
//
// System.out.println("Match " + match("cbk", tokens));
Scanner scanner = new Scanner(System.in);
String firstLine = scanner.nextLine();
String tokens[] = firstLine.split(" ");
int L = Integer.parseInt(tokens[0]), D = Integer.parseInt(tokens[1]), N = Integer.parseInt(tokens[2]);
Set<String> dictionary = new HashSet<String>();
//List<String> patterns = new ArrayList<String>();
for(int i = 0; i < D; i++) {
dictionary.add(scanner.nextLine());
}
for(int i = 0; i < N; i++) {
String pattern = scanner.nextLine();
List<Token> patternTokens = alienSplit(pattern);
int caseCount = 0;
for(String word : dictionary) {
if(match(word, patternTokens)) {
caseCount++;
}
}
System.out.println("Case #" + (i + 1) + ": " + caseCount);
}
}
private static boolean match(String word, List<Token> tokens) {
if(word.length() != tokens.size()) { return false; }
for(int i = 0; i < word.length(); i++) {
if(! tokens.get(i).contains(word.charAt(i))) {
return false;
}
}
return true;
}
private static List<Token> alienSplit(String pattern) {
List<Token> tokens = new ArrayList<Token>();
for(int i = 0; i < pattern.length(); i++) {
if(pattern.charAt(i) == '(') {
int j = pattern.indexOf(')', i);
tokens.add(new Token(pattern.substring(i + 1, j)));
i = j;
} else {
tokens.add(new Token("" + pattern.charAt(i)));
}
}
return tokens;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment