Algorithm problem solution (python)

Reverse string (python)

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

The solution is as follows

There are two solutions:

1. Double pointer
· Initialization: Set two pointers l and r to point to the first and last elements
of the list respectively · Steps: Exchange the corresponding elements of s[l] and s[r], and update the pointer position (l+=1, r-=1), Until the two pointers meet
· Time complexity: O(N)

code show as below

class Solution:
    def reverseString(self, s: List[str]) -> None:
        l,r=0,len(s)-1
        while l<r:
            s[l],s[r]=s[r],s[l]
            l+=1
            r-=1

2. Library functions
· s[::-1] means to reverse the elements
in s · s[:] means all submodules in the array
· s[:]=s[::-1] means to reverse the original array Assign a value to each corresponding position
in s. s=s[::-1] means that s is inverted and assigned to a new object s (you can view the memory address through the id function), which does not match the in-situ modification of the question.

code show as below

class Solution:
    def reverseString(self, s: List[str]) -> None:
        s[:]=s[::-1]

Guess you like

Origin blog.csdn.net/weixin_43372169/article/details/110290542