• 如果您觉得本站非常有看点，那么赶紧使用Ctrl+D 收藏吧

# Leetcode344–翻转字符串

3天前 7次浏览

Leetcode344：翻转字符串

### 文章目录

• Leetcode344–翻转字符串
• 题目描述
• 解题思路

# Leetcode344–翻转字符串

Leetcode344：翻转字符串

## 题目描述

O

(

1

)

O(1)

O(1) 的额外空间解决这一问题。

## 解题思路

``````def reverseString(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
length = len(s)
half = len(s) // 2

# 建立一个tmp临时变量，用于缓存数组着中的元素
for i in range(half):
tmp = s[i]
s[i] = s[length-i-1]
s[length-i-1] = tmp
``````

python可以同时给多个变量赋值，上述代码可以改写为：

``````def reverseString(self, s):
"""
:type s: List[str]
:rtype: void Do not return anything, modify s in-place instead.
"""
length = len(s)
half = l//2
for i in range(half):
s[i], s[length-i-1] = s[length-i-1], s[i]
``````

``````def reverseString(self, s):
"""
:type s: List[str]
:rtype: void Do not return anything, modify s in-place instead.
"""
s.reverse()
``````

n

1

n-1

n1次后完成翻转。

``````def reverseString(self, s):
"""
:type s: List[str]
:rtype: void Do not return anything, modify s in-place instead.
"""
n = len(s)
for i in range(n-1):
t = s.pop(0)
s.insert(n-i-1, t)
``````