leetcode explore 字符串类第一题:反转字符串。相当简单的一个题目
这里把题目贴出来:
Write a function that reverses a string. The input string is given as an array of characters char[].
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
You may assume all the characters consist of printable ascii characters.
Example 1:
Input: ["h","e","l","l","o"]
Output: ["o","l","l","e","h"]
Example 2:
Input: ["H","a","n","n","a","h"]
Output: ["h","a","n","n","a","H"]
题意拆解:
1、输入:列表,只包括字符的列表 2、输出:列表顺序反转 3、注意事项:in-place,即O(1)的空间复杂度,也就是说不需要返回任何数据,原地修改传入的列表
这个题目对于 Python 实现来说相当简单,因为有现成的方法可以调用。参考代码如下:
class Solution(object):
def reverseString(self, s):
"""
:type s: List[str]
:rtype: None Do not return anything, modify s in-place instead.
"""
s.reverse()
1、如果实现列表或者字符串反转?
s = [1, 2, 3]
# 原地修改,没有返回值
s.reverse()
# 返回新的 list
s = reversed(s)
# 特别注意切片的方式,十分灵活,也用得比较多
s = s[::-1]
2、字符串与列表的相互转换
s = [1, 2, 3]
s = "".join(s)
s = list(s)
s = "1,2,3"
s = s.split(",")
点击阅读原文进入题目