uva156 java

·  阅读 29

import java.io.InputStream; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors;

public class Main {

public static void main(String[] args) {
    solution(System.in, new Printer() {
        @Override
        public void p(Object... o) {
            System.out.print(format(o));
        }
    });
}

public static void solution(InputStream in, Printer p) {
    Scanner scanner = new Scanner(in);
    HashMap<ArrayList<Character>, ArrayList<String>> charsToAnagramsMap = new HashMap<>();
    while (scanner.hasNextLine()) {
        String line = scanner.nextLine();
        if (line.trim().equals("#")) {
            break;
        }
        String[] words = line.split(" ");
        for (String word : words) {
            if (!word.isEmpty()) {
                ArrayList<Character> cs = new ArrayList<>();
                char[] chars = word.toLowerCase(Locale.ROOT).toCharArray();
                for (char c : chars) {
                    cs.add(c);
                }
                Collections.sort(cs);
                ArrayList<String> anagrams = charsToAnagramsMap.computeIfAbsent(cs, k -> new ArrayList<>());
                anagrams.add(word);
            }
        }
    }
    charsToAnagramsMap.values().stream().filter(it -> it.size() == 1).map(it -> it.get(0)).sorted().forEach(it -> p.p("%s\n", it));
}

}

interface Printer { void p(Object... o);

default String format(Object... o) {
    String format;
    if (o.length == 1) {
        format = o[0].toString();
    } else {
        Object[] dest = new Object[o.length - 1];
        System.arraycopy(o, 1, dest, 0, dest.length);
        format = String.format(o[0].toString(), dest);
    }
    return format;
}

}

分类:
后端
标签:
分类:
后端
标签:
收藏成功!
已添加到「」, 点击更改