UVa 123|Searching Quickly|字符串处理

来源:互联网 发布:退火算法 matlab 编辑:程序博客网 时间:2024/06/06 18:03

https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=59

题目大意

给定一些句子,其中黑名单外的单词可以为关键字,对于句子的每一个关键字,输出这些句子按关键字排序的结果。

样例输入

istheofandasabut::Descent of ManThe Ascent of ManThe Old Man and The SeaA Portrait of The Artist As a Young ManA Man is a Man but Bubblesort IS A DOG

样例输出

a portrait of the ARTIST as a young manthe ASCENT of mana man is a man but BUBBLESORT is a dogDESCENT of mana man is a man but bubblesort is a DOGdescent of MANthe ascent of MANthe old MAN and the seaa portrait of the artist as a young MANa MAN is a man but bubblesort is a doga man is a MAN but bubblesort is a dogthe OLD man and the seaa PORTRAIT of the artist as a young manthe old man and the SEAa 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();    }}
原创粉丝点击