題目
Task
You are given a string s
. Every letter in s
appears once.
Consider all strings formed by rearranging the letters in s
. After ordering these strings in dictionary order, return the middle term. (If the sequence has a even length n, define its middle term to be the (n/2)
th term.)
Example
For s = "abc"
, the result should be "bac"
. The permutations in order are: "abc", "acb", "bac", "bca", "cab", "cba"
So, The middle term is "bac"
.
Input/Output
[input]
string s
unique letters (2 <= length <= 26)
[output]
a string
middle permutation.
我的答案
def middle_permutation(string):
if string:
if len(string) % 2 == 1:
string = ''.join(sorted(string))
first = string[len(string) // 2]
string = ''.join([i for i in string if i != first])
return first + middle_permutation(string)
else:
string = ''.join(sorted(string, reverse=True))
first = string[len(string) // 2]
string = ''.join([i for i in string if i != first])
return first + string
else:
return ''
其他精彩答案
def middle_permutation(string):
s = sorted(string)
if len(s) % 2 ==0:
return s.pop(len(s) // 2-1) +''.join(s[::-1])
else:
return s.pop(len(s)//2) + middle_permutation(s)
def middle_permutation(string):
s = "".join(sorted(string))
mid = int(len(s) / 2) - 1
if len(s) % 2 == 0:
return s[mid] + (s[:mid] + s[mid + 1:])[::-1]
else:
return s[mid:mid + 2][::-1] + (s[:mid] + s[mid + 2:])[::-1]