My C# recursive solution, very easy to understand


  • 0
    L
        public int MaximumSwap(int num) {
            return int.Parse( helper( num.ToString()) );
        }
        
        public string helper( string s ) {
            if ( s == "" ) return "";
            
            int liMaxIndex = 0;
            for( int i = 1; i < s.Length; ++i ) {
                if ( s[i] >= s[liMaxIndex]) 
                    liMaxIndex = i;
            }
            
            if ( s[liMaxIndex] != s[0] ) {
                return s[liMaxIndex] + s.Substring( 1, liMaxIndex - 1 ) + s[0] + s.Substring( liMaxIndex + 1 );
            } else {
                return s[0] + helper( s.Substring( 1));
            }
        }
    

Log in to reply
 

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