繁体   English   中英

给定一组字符,如何仅通过重新排列字符来显示具有更高字典顺序的字符串?

[英]Given a set of characters, how can you display the string with a higher lexicographical order, only by rearranging the characters?

假设您有字符串cana 字典顺序高于此的字符串将是cnaa 有什么方法可以做到这一点,比从右到左检查每个字符更快吗?

#include <string>
#include <algorithm>

void swap_chars(char &a, char &b) {
  char m = a;
  a = b;
  b = m;
}

std::string next(std::string str) {
  for (int i=str.length()-1; i>0; i--)
    if (str.at(i-1) < str.at(i)) {
      swap_chars(str.at(i-1), str.at(i));
      std::sort(str.begin()+i, str.end());
      break;
    }
  return str;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM