📌  相关文章
📜  根据前缀按字典顺序对字符串数组进行排序

📅  最后修改于: 2021-04-27 21:16:31             🧑  作者: Mango

给定大小为N的字符串数组arr [] ,任务是按字典顺序对字符串数组进行排序,如果同时对任意两个字符串A和字符串B进行排序,则如果字符串A是字符串B的前缀,则字符串B应该出现按排序顺序。

例子:

方法:想法是使用内置的sort函数使用下面的比较器函数对给定的字符串数组进行排序。比较器函数用于使用C++中的compare()函数检查是否有任何字符串作为另一个字符串的子字符串出现,然后,应按其长度的降序排列它们。

bool my_compare(string a, string b)
{
    // If any string is a substring then
    // return the size with greater length
    if (a.compare(0, b.size(), b) == 0
        || b.compare(0, a.size(), a) == 0)
        return a.size() & gt;
    b.size();
  
    // Else return lexicographically
    // smallest string
    else return a & lt;
    b;
}

下面是上述方法的实现:

C++
// C++ program for the above approach
  
#include 
using namespace std;
  
// Function to print the vector
void Print(vector v)
{
    for (auto i : v)
        cout << i << endl;
}
  
// Comparator function to sort the
// array of string wrt given conditions
bool my_compare(string a, string b)
{
    // Check if a string is present as
    // prefix in another string, then
    // compare the size of the string
    // and return the larger size
    if (a.compare(0, b.size(), b) == 0
        || b.compare(0, a.size(), a) == 0)
  
        return a.size() > b.size();
  
    // Else return lexicographically
    // smallest string
    else
        return a < b;
}
  
// Driver Code
int main()
{
    // GIven vector of strings
    vector v = { "batman", "bat", "apple" };
  
    // Calling Sort STL with my_compare
    // function passed as third parameter
    sort(v.begin(), v.end(), my_compare);
  
    // Function call to print the vector
    Print(v);
    return 0;
}


输出:
apple
batman
bat

时间复杂度: O(N * log N)
辅助空间: O(1)