[Leetcode] 344. Reverse String

No344. Reverse character string

topic

Write a function whose role is to reverse the input string. The input string is given in the form of a character array char[].

Don't allocate extra space for another array, you must modify the input array in place and use O(1) extra space to solve this problem.

You can assume that all characters in the array are printable characters in the ASCII code table.

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

Ideas

Traverse exchange, Python unique exchange statement is used here, which is a kind of syntactic sugar

Problem-solving code (Python3)

class Solution:
    def reverseString(self, s: List[str]) -> None:
        n = len(s)
        for i in range(n//2):
            s[i],s[n-i-1] = s[n-i-1],s[i]

Complexity analysis:

  • Time complexity O(n)
  • Space complexity O(1)

operation result:

Insert picture description here

Guess you like

Origin blog.csdn.net/Xiao_Spring/article/details/113776647