【问题标题】:Sorting string in descending order.按降序对字符串进行排序。
【发布时间】:2017-01-09 10:40:37
【问题描述】:

C++ (STL) 中是否有一个字符串函数可以按降序对字符串进行排序。 如果不是,如何在 O(n) 时间内按降序对字符串进行排序。

【问题讨论】:

  • 函数调用sort
  • @Yathartha 你知道用 O(n) 排序的算法吗?
  • @VladfromMoscow,计数排序非常接近。它不适用于字符串(无论如何直接),但它是一个示例。
  • 如果标准库中有合适的函数,是否可以花费比 O(n) 更长的时间?或者你想要库函数中的 O(n) 吗?

标签: c++ stl


【解决方案1】:

最简单的方法是 std::sort 它,然后 std::reverse 它。 排序来自算法。 反向来自实用程序。

#include <iostream>
#include <string>
#include <algorithm>
#include <utility>

int main(){

    std::string str = "Hello Beep 5412";

    std::cout << "normal string:" << std::endl;
    std::cout << str << std::endl;


    std::sort(str.begin(), str.end()); //sort it
    std::reverse(str.begin(), str.end()); //reverse it

    std::cout << "\nsorted, descending:" << std::endl;
    std::cout << str << std::endl;

    system("pause");
    return 0;
}

输出:

normal string:
Hello Beep 5412

sorted, descending:
polleeeHB5421  

【讨论】:

  • std::sortstd::greater 一起使用比反转使用简单得多:sort(begin(str), end(str), std::greater&lt;char&gt;());
【解决方案2】:

C++ 中有一个函数可以对字符串进行排序,您可以通过告诉它与std::greater 而不是std::less 比较来使其降序排序。

但是,它不会在 O(n) 时间内排序(它将是 O(n log n))。为此,您需要使用桶排序。

【讨论】:

    【解决方案3】:

    如果您需要线性时间,则不能使用任何通用排序算法(它们都是O(n log n) 平均情况)。所以:不,标准库中没有一个合适的函数。

    Pigeonhole sort 或其他桶排序会起作用:只需跟踪 256 个可能字符中每个字符的频率,然后重写字符串。

    请注意,您仍然需要了解您的 char 值所需的词法顺序,但是您只需通过以正确(降序)顺序遍历您的存储桶来重写您的字符串。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-21
      • 2013-06-05
      • 1970-01-01
      • 2019-04-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多