Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
最好的方法是什么 - 给定一个字符串 A 和字符串集合 C,按照字符串中 A 的位置的非递减顺序对集合中的字符串进行排序。
例如,
A= abc C= [deabc, abc, dabc, dad] Sorted C= [abc, dabc, deabc]
我的想法是遍历集合并将其放入 HashMap/Dictionary 中,其中 A 在 C[i] 中的位置作为索引。然后从 HashMap 构造排序集合。这不是家庭作业问题。只是想知道这样做的有效方式/算法。任何指针都会有所帮助。
这是使用 LINQ 的一种简单方法:
var SortedC = C.OrderBy (d => d.IndexOf(A)).ToArray();
请注意,不包含 A 的字符串将在开头进行排序,因为IndexOf返回-1。此外,在同一索引处具有 A 的字符串的行为是未定义的,并且将按任意顺序返回,除非您提供.ThenBy排序来处理这些行为。
IndexOf
-1
.ThenBy
stringsArray.OrderBy(s => s.IndexOf("a"))