题目
对于一个给定的字符串数组,请找到一种拼接顺序,使所有小字符串拼接成的大字符串是所有可能的拼接中字典序最小的。
给定一个字符串数组strs,同时给定它的大小,请返回拼接成的串。
测试样例:
[“abc”,”de”],2
“abcde”
思路
定义比较函数str1+str2<=str2+str1,然后自定义快排。
代码
class Prior:
def mycmp(self, str1, str2):
return str1 + str2 >= str2 + str1
def partition(self, strs, begin, end):
tmp = strs[begin]
while begin < end:
while begin < end and self.mycmp(strs[end], tmp):
end -= 1
if begin < end:
strs[begin] = strs[end]
while begin < end and self.mycmp(tmp, strs[begin]):
begin += 1
if begin < end:
strs[end] = strs[begin]
strs[begin] = tmp
return begin
def sort(self, strs, begin, end):
if begin < end:
parti = self.partition(strs, begin, end)
self.sort(strs, begin, parti)
self.sort(strs, parti + 1, end)
def findSmallest(self, strs, n):
# write code here
self.sort(strs, 0, n - 1)
return ''.join(strs)