c++ & python simple solutions


  • 0
    Z

    brute force solution, you don't need to think...
    c++ solution

    class Solution {
    public:
        int maximumSwap(int num) {
            string s = to_string(num);
            for ( int i = 0; i < s.size(); ++i )
                for ( int j = i + 1; j < s.size(); ++j ) {
                    swap(s[i], s[j]);
                    num = max(num, stoi(s));
                    swap(s[i], s[j]);
                }
            return num;
        }
    };
    
    // 111 / 111 test cases passed.
    // Status: Accepted
    // Runtime: 3 ms
    

    python solution

    class Solution(object):
        def maximumSwap(self, num):
            """
            :type num: int
            :rtype: int
            """
            s = list(str(num))
            for i in xrange(len(s)):
                for j in xrange(i+1, len(s)):
                    s[i], s[j] = s[j], s[i]
                    num = max(num, int(''.join(s)))
                    s[i], s[j] = s[j], s[i]
            return num
    
    # 111 / 111 test cases passed.
    # Status: Accepted
    # Runtime: 39 ms
    

Log in to reply
 

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