【python】对由大小写字母组成的字符数组排序?
2019-07-25 本文已影响0人
阿牛02
题目:有一个由大小写字母组成字符串,请对它进行重新组合,使得其中的所有小写字母排在大写字母的前面(大小写母或小写字母之间不要求保持原来次序)。
分析:用两个索引分别指向字符串的首和尾,首索引正向遍历字符串,找到第一个大写字母,尾索引逆向遍历字符串,找到第一个小写字母,交换两个索引位置的字符,然后将两个索引沿着相应的方向继续向前移动,重复上述步骤,直到首索引大于或等于尾索引为止。
code:
def ReverseArray(ch):
lens = len(ch)
begin = 0
end = lens - 1
while begin < end:
while ch[begin] >= 'a' and ch[end] <= 'z' and end > begin:
begin += 1
while ch[end] >= 'A' and ch[end] <= 'Z' and end > begin:
end -= 1
temp = ch[begin]
ch[begin] = ch[end]
ch[end] = temp
if __name__ == "__main__":
ch = list("AbcDef")
ReverseArray(ch)
i = 0
while i < len(ch):
print(ch[i])
i += 1
