题解 | #字符串排序#
字符串排序
https://www.nowcoder.com/practice/5af18ba2eb45443aa91a11e848aa6723
import sys
words = []
for line in sys.stdin:
if line == '\n':
break
if line.strip().isnumeric():
continue
else:
words.append(line.strip())
# 快速排序
def quick_sort(src: list[str], left: int, right: int):
i = left
j = right
if left >= right:
return
while i < j:
# 基准值在位置 i
while i < j and is_smaller(src[i], src[j]):
j -= 1
if i < j:
src[i], src[j] = src[j], src[i]
# 基准值在位置 j
while i < j and is_smaller(src[i], src[j]):
i += 1
if i < j:
src[i], src[j] = src[j], src[i]
quick_sort(src, left, i - 1)
quick_sort(src, j + 1, right)
def is_smaller(word1: str, word2: str):
min_len = min(len(word1), len(word2))
for i in range(min_len):
if word1[i] < word2[i]:
return True
elif word1[i] > word2[i]:
return False
if len(word1) > len(word2):
return False
else:
return True
quick_sort(words, 0, len(words) - 1)
print('\n'.join(words))
深信服公司福利 885人发布