前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >leetcode: explore-strings-32 反转字符串

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

作者头像
用户7685359
发布2020-08-24 16:24:18
2620
发布2020-08-24 16:24:18
举报
文章被收录于专栏:FluentStudyFluentStudy

leetcode explore 字符串类第一题:反转字符串。相当简单的一个题目

题目分析

这里把题目贴出来:

代码语言:javascript
复制
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 实现来说相当简单,因为有现成的方法可以调用。参考代码如下:

代码语言:javascript
复制
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、如果实现列表或者字符串反转?

代码语言:javascript
复制
s = [1, 2, 3]
# 原地修改,没有返回值
s.reverse()

# 返回新的 list
s = reversed(s)

# 特别注意切片的方式,十分灵活,也用得比较多
s = s[::-1]

2、字符串与列表的相互转换

代码语言:javascript
复制
s = [1, 2, 3]
s = "".join(s)
s = list(s)

s = "1,2,3"
s = s.split(",")

点击阅读原文进入题目

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2019-11-12,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 FluentStudy 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目分析
  • 参考答案
  • 面试题引申
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档