简体   繁体   中英

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

Let's say you have the string cana . The string with the lexicographical order higher than that, would be cnaa . Is there any way you could do that, faster than just checking from right to left for every character?

#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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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