字符串匹配,这里我用了JAVA的正则,懒的去写匹配方法了,后来想了想其实匹配方法手写其实也是可以的,JAVA的时间和内存和C系真不是一个数量级的,不到万不得已还是别用了。。这里注意保存已有的word匹配结果可以大大提高效率,就是代码里那个map
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.regex.Pattern;
public class Main
{
static final String PAT = "[A-Z]*";
static Map<String, String> map = new HashMap<String, String>();
static String find(List<String> dict, String word)
{
if (map.containsKey(word))
return map.get(word);
StringBuilder sb = new StringBuilder(PAT);
for (char c : word.toCharArray())
sb.append(c).append(PAT);
Pattern p = Pattern.compile(sb.toString());
boolean find = false;
String res = null;
for (String s : dict)
{
if (p.matcher(s).find())
{
if (find)
return null;
find = true;
res = s;
}
}
map.put(word, res);
return res;
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
sc.nextLine();
List<String> dict = new ArrayList<String>();
for (int t = 0; t < N; t++)
{
if (t > 0)
System.out.println();
int n = sc.nextInt();
sc.nextLine();
dict.clear();
map.clear();
while (n-- > 0)
dict.add(sc.nextLine());
String line;
StringBuilder sb = new StringBuilder();
while (!(line = sc.nextLine()).endsWith("#"))
sb.append(line).append('\n');
sb.append(line.substring(0, line.length() - 1));
boolean can = true;
boolean inWord = false;
StringBuilder res = new StringBuilder();
String word = "";
for (char c : sb.toString().toCharArray())
{
if (c >= 'A' && c <= 'Z')
{
inWord = true;
word += c;
}
else
{
if (inWord)
{
String temp = find(dict, word);
if (temp == null)
{
can = false;
break;
}
else
res.append(temp);
word = "";
}
res.append(c);
inWord = false;
}
}
if (inWord && can)
{
String temp = find(dict, word);
if (temp == null)
can = false;
else
res.append(temp);
}
if (can)
System.out.println(res);
else
System.out.println("AMBIGUITY");
}
sc.close();
}
}