📌  相关文章
📜  根据给定的顺序对字符串数组进行排序

📅  最后修改于: 2021-09-03 14:49:26             🧑  作者: Mango

鉴于字符串字[]和字母的顺序一个数组,我们的任务是根据给定的顺序排列进行排序。假设字典和单词只包含小写字母。

例子:

方法:为了解决上面提到的问题,我们需要按照给定的顺序维护每个字符的优先级。为此,请使用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

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live