leetcode: explore-strings-32 反转字符串

时间:2022-07-23
本文章向大家介绍leetcode: explore-strings-32 反转字符串,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

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(",")

点击阅读原文进入题目