8-liner C++ solution to store last position of each digit

  • 0
        int maximumSwap(int n) {
            string s = to_string(n);
            unordered_map<char, int> lastPos; // last position of digit
            for (int i = 0; i < s.size(); ++i) lastPos[s[i]] = i;
            for (int i = 0; i < s.size(); ++i)
                for (char d = '9'; d > s[i]; --d)
                    if (lastPos[d] > i)
                        return swap(s[i], s[lastPos[d]]), stoi(s);
            return stoi(s);

Log in to reply

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