> For the complete documentation index, see [llms.txt](https://l1nwatch.gitbook.io/interview_exercise/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://l1nwatch.gitbook.io/interview_exercise/bian-cheng-ti-hui-zong/teng-xun-2017-shu-qi-shi-xi-sheng-bian-cheng-ti/suan-fa-ji-chu-zi-fu-yi-wei.md).

# 算法基础-字符移位

## 题目描述

小Q最近遇到了一个难题：把一个字符串的大写字母放到字符串的后面，各个字符的相对位置不变，且不能申请额外的空间。 你能帮帮小Q吗？

**输入描述:**

输入数据有多组，每组包含一个字符串s，且保证:1<=s.length<=1000.

**输出描述:**

对于每组数据，输出移位后的字符串。

**输入例子:**

AkleBiCeilD

**输出例子:**

kleieilABCD

## 分析

几个知识点：

* 不需要额外空间的两个数交换操作
* 思路是从后面开始遍历，遇到小写字母就将其与首位交换位置，其余位置依次移位

## Python 代码实现

最终提交如下：

```python
def no_extra_space_swap(a, b):
    """
    不能构建额外空间, 那么交换移动元素使用位操作的那个版本 swap()
    原理是异或了 2 次相当于没有异或
    :param a: 'a'
    :param b: 'b'
    :return: 'b', 'a'
    """
    a, b = ord(a), ord(b)
    a ^= b
    b ^= a
    a ^= b
    return chr(a), chr(b)


def post_order_move(s):
    """
    把一个字符串的大写字母放到字符串的后面，各个字符的相对位置不变，且不能申请额外的空间。
    :param s: "AkleBiCeilD"
    :return: "kleieilABCD"
    """
    s = list(s)
    last = len(s) - 1
    for i in range(last, -1, -1):
        if s[i].islower():
            continue
        else:
            s[i], s[last] = no_extra_space_swap(s[i], s[last])
            for j in range(i, last - 1):
                s[j], s[j + 1] = no_extra_space_swap(s[j], s[j + 1])
            last -= 1

    return "".join(s)

import sys
for line in sys.stdin:
    a = line.strip()
    print post_order_move(a)
```
