简体   繁体   English

使用Array.sort对字符串数组中的字母进行排序

[英]Using Array.sort to sort anagrams in a String array

I would like to sort an array based on their group of anagrams. 我想根据他们的字谜组对数组进行排序。

For Example: 例如:

[anew, sale, wane, ales, ascent, seal, wean, leas, secant]

Should output: 应该输出:

[anew, wane, wean, ales, leas, sale, seal, ascent, secant]

Or it could output anagrams on any order as long as they are grouped together. 或者,只要将它们组合在一起,它就可以按任何顺序输出字谜。

So I tried doing this: 所以我尝试这样做:

Arrays.sort(array, (s1, s2) -> {
   if (s1.length < s2.length)
        return -1;
    else if (s1.length > s2.length)
        return 1;
    else
        return s1.compareTo(s2);
   });

But I got this: 但是我得到了:

[secant, leas, wean, seal, ascent, ales, wane, sale, anew]

I know the issue is in the comparator but I can't figure out what is going wrong. 我知道问题出在比较器中,但我无法弄清楚出了什么问题。

Your algorithm cannot possibly work, because sorting is achieved by comparing elements locally. 您的算法可能无法工作,因为排序是通过本地比较元素来实现的。 To sort by number of anagrams you need to remember what strings are anagrams of one another. 要按字谜数字排序,您需要记住哪些字符串是彼此的字谜。 This is not a decision, which is possible by comparing two elements without context. 这不是决定,可以通过比较两个没有上下文的元素来实现。 You need to identify and collect the anagrams first. 您需要先识别并收集字谜。 Then you can construct the result list. 然后,您可以构造结果列表。

package sandbox;

import java.util.Arrays;
import java.util.List;

public class AnagramSort {
    private static final String[] DATA = { "anew", "sale", "wane", "ales", "ascent", "seal", "wean", "leas", "secant" };

    public static void main(String[] args) {
        List<String> data = Arrays.asList(DATA);

        System.out.println(data);
        data.sort(AnagramSort::isAnagram);
        System.out.println(data);
    }

    public static int isAnagram(String a, String b) {
        char[] s1 = a.toCharArray();
        char[] s2 = b.toCharArray();
        if (s1.length < s2.length)
            return -1;
        else if (s1.length > s2.length)
            return 1;

        Arrays.sort(s1);
        Arrays.sort(s2);
        return Arrays.compare(s1,s2);

    }
}

Results in: 结果是:

[sale, ales, seal, leas, anew, wane, wean, ascent, secant] [销售,啤酒,海豹,利物,重新,衰弱,断奶,上升,割线]

That's probably close to what you need with some tuning done to the isAnagram method (I wrote a crude quick version for this test, and I am not checking is one string is an anagram contained fully inside another larger string). 通过对isAnagram方法进行一些调整,这可能接近您所需要的(我为该测试编写了一个粗略的快速版本,但我没有检查一个字符串是否完全包含在另一个更大的字符串中的一个字谜)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM