简体   繁体   English

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

[英]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 .假设您有字符串cana The string with the lexicographical order higher than that, would be cnaa .字典顺序高于此的字符串将是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;
}

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

相关问题 给定一个字符串,我如何仅将另一个字符串中的唯一字符添加到其中? - Given a string, how can I add only unique characters from another string to it? 通过重新排列字符来查找字符串中的所有回文子字符串 - Find All Palindrome Substrings in a String by Rearranging Characters 按字典顺序打印给定字符串的所有字母组合的算法 - Algorithm to print all combination of letters of the given string in lexicographical order 查找可以由保留字符串顺序的第一和第二个字符串的所有字符组成的给定字符串的所有交织 - Find all interleavings of given strings that can be formed from all the characters of first and second string where order of characters is preserved 查找字符串是否仅包含给定字符集的最佳方法/算法 - Best way/algorithm to find out if a string consists of only a given set of characters 如何在字符串中查找一组字符 - How to find a set of characters in a string 字符集中字符的顺序 - Order of the characters in character set 如何在字符串中获取 std::set 字符作为字符串? - How can I get a std::set of characters in a string, as strings? 标记字符串,接受CPP中给定字符集之间的所有内容 - tokenizing string , accepting everything between given set of characters in CPP C ++-确定给定的字符串是否仅具有Furigana字符 - C++ - Determine whether given string has only Furigana Characters
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM