鉴于字符串字[]和字母的顺序一个数组,我们的任务是根据给定的顺序排列进行排序。假定字典和单词仅包含小写字母。
例子:
Input: words = {“hello”, “geeksforgeeks”}, order = “hlabcdefgijkmnopqrstuvwxyz”
Output: “hello”, “geeksforgeeks”
Explanation:
According to the given order ‘h’ occurs before ‘g’ and hence the words are considered to be sorted.
Input: words = {“word”, “world”, “row”}, order = “worldabcefghijkmnpqstuvxyz”
Output: “world”, “word”, “row”
Explanation:
According to the given order ‘l’ occurs before ‘d’ hence the words “world” will be kept first.
方法:要解决上述问题,我们需要按给定的顺序保持每个字符的优先级。为此,请使用Map Data Structure 。
- 以给定的顺序进行迭代,并将字符的优先级设置为其索引值。
- 使用自定义比较器函数对数组进行排序。
- 在比较器函数,通过迭代最小尺寸的两个词之间的单词,并尝试找到第一个不同的字符,具有较低的优先级值字符将是较小的字字。
- 如果单词具有相同的前缀,则大小较小的单词就是较小的单词。
下面是上述方法的实现:
// C++ program to sort an array
// of strings based on the given order
#include
using namespace std;
// For storing priority of each character
unordered_map mp;
// Custom comparator function for sort
bool comp(string& a, string& b)
{
// Loop through the minimum size
// between two words
for (int i = 0;
i < min(a.size(), b.size());
i++) {
// Check if the characters
// at position i are different,
// then the word containing lower
// valued character is smaller
if (mp[a[i]] != mp[b[i]])
return mp[a[i]] < mp[b[i]];
}
/* When loop breaks without returning, it
means the prefix of both words were same
till the execution of the loop.
Now, the word with the smaller size will
occur before in sorted order
*/
return (a.size() < b.size());
}
// Function to print the
// new sorted array of strings
void printSorted(vector words,
string order)
{
// Mapping each character
// to its occurance position
for (int i = 0; i < order.size(); i++)
mp[order[i]] = i;
// Sorting with custom sort function
sort(words.begin(), words.end(), comp);
// Printing the sorted order of words
for (auto x : words)
cout << x << " ";
}
// Driver code
int main()
{
vector words
= { "word", "world", "row" };
string order
= { "worldabcefghijkmnpqstuvxyz" };
printSorted(words, order);
return 0;
}
输出:
world word row