集册 Java实例教程 Java打印大于大小阈值的所有置换组

Java打印大于大小阈值的所有置换组

欢马劈雪     最近更新时间:2020-01-02 10:19:05

488
Java打印大于大小阈值的所有置换组

import java.util.*;
/** 
 来自 n o w j a v a . c o m - 时代Java**/

import java.io.*;


public class Anagrams {

    public static void main(String[] args) {

        int minGroupSize = Integer.parseInt(args[1]);


        // Read words from file and put into a simulated multimap

        Map<String, List<String>> m = new HashMap<String, List<String>>();


        try {

            Scanner s = new Scanner(new File(args[0]));

            while (s.hasNext()) {

                String word = s.next();

                String alpha = alphabetize(word);
                /* 
                *来 自
                 N o w J a v a . c o m - 时代Java
                */

                List<String> l = m.get(alpha);

                if (l == null)

                    m.put(alpha, l = new ArrayList<String>());

                l.add(word);

            }

        } catch (IOException e) {

            System.err.println(e);

            System.exit(1);

        }


        // Print all permutation groups above size threshold

        for (List<String> l : m.values())

            if (l.size() >= minGroupSize)

                System.out.println(l.size() + ": " + l);

    }


    private static String alphabetize(String s) {

        char[] a = s.toCharArray();

        Arrays.sort(a);

        return new String(a);

    }

}


展开阅读全文