您如何通过这些字母排序以下单词?
string[] _words1 = {"road", "apple", "maple", "roam", "wind"};
string _alphabet1 = "irqjfomqwijapfpdpwe";
Run Code Online (Sandbox Code Playgroud)
其中每个单词的顺序由_alphabet1确定,但诀窍是"road"应该在"漫游"之后,因为"r"类似,"o"类似","a"相似,"d"来在_alphabet1中的"m"之后
使用内置数组.Sort()及其重载.
这个问题出现在面试中,我无法做到.采访者说应该使用.Sort()重载来简化代码.
您可以定义自己的扩展类Comparer.基本上,您可以使用您正在使用的修改后的"字母"来定义两个字符串相对于彼此的排序方式.
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;
}
}
Run Code Online (Sandbox Code Playgroud)
然后在你打电话时实例化它Array.Sort:
string[] _words1 = { "road", "apple", "maple", "roam", "wind" };
Array.Sort(_words1, new MyComparer());
Run Code Online (Sandbox Code Playgroud)
_words1排序后的内容:
roam
road
maple
wind
apple
Run Code Online (Sandbox Code Playgroud)