https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=59
题目大意
给定一些句子,其中黑名单外的单词可以为关键字,对于句子的每一个关键字,输出这些句子按关键字排序的结果。
样例输入
is
the
of
and
as
a
but
::
Descent of Man
The Ascent of Man
The Old Man and The Sea
A Portrait of The Artist As a Young Man
A Man is a Man but Bubblesort IS A DOG
样例输出
a portrait of the ARTIST as a young man
the ASCENT of man
a man is a man but BUBBLESORT is a dog
DESCENT of man
a man is a man but bubblesort is a DOG
descent of MAN
the ascent of MAN
the old MAN and the sea
a portrait of the artist as a young MAN
a MAN is a man but bubblesort is a dog
a man is a MAN but bubblesort is a dog
the OLD man and the sea
a PORTRAIT of the artist as a young man
the old man and the SEA
a portrait of the artist as a YOUNG man
题解
Java大法好。
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Scanner;
public class Main {
class Pair<K extends Comparable<K>, V extends Comparable<V>, P> implements Comparable<Pair<K, V, P>> {
K k; V v; P p;
Pair(K k, V v, P p) {
this.k = k;
this.v = v;
this.p = p;
}
@Override
public int compareTo(Pair<K, V, P> o) {
int a = k.compareTo(o.k);
if (a != 0) return a;
else return v.compareTo(o.v);
}
}
private HashSet<String> ignores = new HashSet<>();
private ArrayList<Pair<String, Integer, String>> sentences = new ArrayList<>();
String join(String[] str, int from, int to, String d) {
if (from >= to || from >= str.length || to > str.length) return "";
StringBuilder sb = new StringBuilder(str[from]);
for (int i = from + 1; i < to; ++i)
sb.append(d).append(str[i]);
return sb.toString();
}
Main() {
Scanner scanner = new Scanner(System.in);
while (true) {
String keyword = scanner.nextLine();
if (!keyword.equals("::"))
ignores.add(keyword.toLowerCase());
else
break;
}
int s = 0;
while (scanner.hasNext()) {
String line = scanner.nextLine();
String keys[] = line.toLowerCase().split(" ");
++s;
for (int i = 0; i < keys.length; ++i) {
String key = keys[i].toLowerCase();
if (!ignores.contains(key))
sentences.add(new Pair<>(key, s, join(keys, 0, i, " ") + " " + key.toUpperCase() + " " + join(keys, i + 1, keys.length, " ")));
}
}
sentences.sort(null);
sentences.stream().map(p -> p.p).forEach(line -> {
if (!line.trim().isEmpty())
System.out.println(line.trim());
});
}
public static void main(String[] args) {
new Main();
}
}