按字母顺序排列单词

Order words by alphabet

你会如何按照这些字母对以下单词进行排序?

string[] _words1 = {"road", "apple", "maple", "roam", "wind"};
string _alphabet1 = "irqjfomqwijapfpdpwe";

其中单词的每个顺序由_alphabet1 确定,但诀窍是 "road" 应该在 "roam" 之后,因为 "r" 相似,"o" 相似","a"类似,_alphabet1

中"m"后面是"d"

使用内置数组 .Sort() 及其重载。

这个问题是面试出来的,我做不出来。面试官说应该用.Sort()重载来简化代码

您可以定义自己的 class 来扩展 Comparer。基本上,您使用您正在使用的修改后的 "alphabet" 来定义两个字符串相对于彼此的排序方式。

public class MyComparer : Comparer<string>
{
    private string _alphabet1 = "irqjfomqwijapfpdpwe";

    public override int Compare(string x, string y)
    {
        var minLength = Math.Min(x.Length, y.Length);

        for (var i = 0; i < minLength; i++)
        {
            var stringXpos = _alphabet1.IndexOf(x[i]);
            var stringYpos = _alphabet1.IndexOf(y[i]);

            if (stringXpos < stringYpos)
                return -1;

            if (stringYpos < stringXpos)
                return 1;
        }

        return x.Length < y.Length ? -1 : (x.Length > y.Length) ? 1 : 0;
    }
}

然后在调用Array.Sort时实例化它:

string[] _words1 = { "road", "apple", "maple", "roam", "wind" };

Array.Sort(_words1, new MyComparer());

_words1 的内容,排序后:

roam
road
maple
wind
apple