leetcode 344. Reverse String 解法 python

一.问题描述

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"]

二.解题思路

题目要求不能多开数组来保存,反转string就是将数组沿中心轴将两边互换。

也就是将 sting[i]和string[len-i]互换,len是string的长度。

需要注意的是对边界的处理,明白len/2对应的索引是哪半边,在len为奇数和len为偶数的时候分别对应哪些位置。

时间复杂度O(N),空间复杂度O(1)。

之后有高效算法会更新。

更多leetcode算法题解法请关注我的专栏leetcode算法从零到结束或关注我。

欢迎大家一起套路一起刷题一起ac。

三.源码

class Solution:
    def reverseString(self, s: List[str]) -> None:
        """
        Do not return anything, modify s in-place instead.
        """
        len_s=len(s)
        for i in range(int(len_s/2)):
            s[i],s[len_s-i-1]=s[len_s-i-1],s[i]

 

你可能感兴趣的:(leetcode算法从零到结束)