原题
翻转字符串
样例:
给出 s = "hello", 返回 "olleh".
解题思路
- 方法一:在Python中string可以看做是字符的数组,所以直接翻转字符数组
- 方法二:碰撞型指针,两个指针,从两头对调
完整代码
# method 1
class Solution(object):
def reverseString(self, s):
"""
:type s: str
:rtype: str
"""
return s[::-1]
# method 2
class Solution(object):
def reverseString(self, s):
"""
:type s: str
:rtype: str
"""
elements = list(s)
left, right = 0, len(elements) - 1
while left < right:
elements[left], elements[right] = elements[right], elements[left]
left += 1
right -= 1
return "".join(elements)