[CPP]3ms easy understanding code


  • 0
    Z
    class Solution {
    public:
        int maximumSwap(int num) {
           std::string numString = std::to_string(num);
           bool notSwaped = true;
           for (size_t i = 0; notSwaped && i < numString.size(); ++i) {
              auto maxChar = std::max_element(numString.begin() + i,numString.end());
              if (*maxChar != numString.at(i)) {
                  auto maxCharLast = std::find(numString.rbegin(),numString.rend()-i,*maxChar);
                  std::swap(*maxCharLast,numString.at(i));
                  notSwaped = false;
              }
          }
          return std::stoi(numString);
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.