【刷题打卡】344. 反转字符串

97 阅读1分钟

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第9天,点击查看活动详情

一、题目描述:

344. 反转字符串 - 力扣(LeetCode) (leetcode-cn.com)

编写一个函数,其作用是将输入的字符串反转过来。输入字符串以字符数组 s 的形式给出。

不要给另外的数组分配额外的空间,你必须原地修改输入数组、使用 O(1) 的额外空间解决这一问题。

 

示例 1:

输入:s = ["h","e","l","l","o"]
输出:["o","l","l","e","h"]

示例 2:

输入:s = ["H","a","n","n","a","h"]
输出:["h","a","n","n","a","H"]

提示:

  • 1 <= s.length <= 10^5
  • s[i] 都是 ASCII 码表中的可打印字符

二、思路分析:

遍历半个字符串,依次将首尾2个字符对换位置,直到字符串中间
第一步:考虑递归退出条件:
1.当起始位置=结束位置时,即剩中间一个字符时
2.当起始位置>结束位置时,即字符总数为偶数,中间2个字符对换位置之后
第二步:设计递归主过程:
1.对换当前起始和结束位置的2个字符
2.起始位置+1,结束位置-1
第三步:起始和结束位置初始化,并调用递归

三、AC 代码:

class Solution(object):
    def reverseString(self, s):
        """
        :type s: List[str]
        :rtype: None Do not return anything, modify s in-place instead.
        """
        def helper(start_idx, end_idx, s):
            if start_idx >= end_idx:
                return s
            s[start_idx], s[end_idx] = s[end_idx], s[start_idx]
            s = helper(start_idx + 1, end_idx - 1, s)

        return helper(0, len(s) - 1, s)        

范文参考

执行用时 :40 ms, 在所有 golang 提交中击败了98.01%的用户 内存消耗 :6.2 MB, 在所有 golang 提交中击败了100.00% - 反转字符串 - 力扣(LeetCode)

「代码随想录」带你搞定字符串!344. 反转字符串:【双指针法】详解 - 反转字符串 - 力扣(LeetCode)

左右双指针交换次序和直接reverse翻转方法 - 反转字符串 - 力扣(LeetCode)