反转字符串(LeetCode)

题目

编写一个函数,其作用是将输入的字符串反转过来。输入字符串以字符数组 的形式给出。

不要给另外的数组分配额外的空间,你必须**原地修改输入数组** 、使用 的额外空间解决这一问题。

解题

python 复制代码
def reverse_string(s):
    left = 0
    right = len(s) - 1

    while left < right:
        # 交换左右指针所指的元素
        s[left], s[right] = s[right], s[left]
        # 移动指针
        left += 1
        right -= 1


# 测试例子
s = ['h', 'e', 'l', 'l', 'o']
reverse_string(s)
print("反转后的数组:", s)

反转后的数组: ['o', 'l', 'l', 'e', 'h']

相关推荐
zqy02271 天前
HTTP的Web服务测试在Python中的实现
python·网络协议·http
豌豆花下猫1 天前
Python 潮流周刊#119:Google 停止开发 Pytype!
后端·python·ai
千册1 天前
pyside6 的pdf显示测试 -- 01
开发语言·python·pdf
诸葛务农1 天前
光电对抗:多模/复合制导中算法和软件平台
算法
Swift社区1 天前
LeetCode 378 - 有序矩阵中第 K 小的元素
算法·leetcode·矩阵
阿拉丁的梦1 天前
【maxscript】矩阵对齐-武器残影
python·3dsmax
mortimer1 天前
Python 异常处理进阶:从 `traceback` 细节到稳健的多语言处理器
python
墨染点香1 天前
LeetCode 刷题【73. 矩阵置零】
算法·leetcode·矩阵
tqs_123451 天前
redis zset score的计算
java·算法