Leetcode brushing record (8): 344 reverse string

Brush questions website: Leetcode

Difficulty: easy

Language: Python

Plan : From easy -> to medium -> to hard.

1. 344 reverse string

1.1 Subject:

Write a function that reverses the input string. The input string sis .

Don't allocate extra space to another array, you must fix the problem by modifying the input array in place, using O(1)the extra space.

  • Example 1
输入:s = ["h","e","l","l","o"]
输出:["o","l","l","e","h"]
  • Example 2
输入:s = ["H","a","n","n","a","h"]
输出:["h","a","n","n","a","H"]

1.2 Thinking and Analysis:

This question is different from the previous one, which is to input an array of characters, but the practice is the same.

By convention, you need to use double pointers to find, just swap the leftmost and rightmost characters, this problem is relatively simple.

The complete code is as follows:

class Solution:
    def reverseString(self, s: List[str]) -> None:
        """
        Do not return anything, modify s in-place instead.
        """
        left = 0
        right = len(s)-1
        while left<right:
            a = s[right]
            s[right] = s[left]
            s[left] = a
            right-=1
            left+=1

The execution result shows that it beats 67.76% of users.
insert image description here

1.3 Summary

This question feels like a simple two-pointer problem. After doing the previous exercises, I completed this problem in one go and completed it in less than a few minutes. I hope that I will be so good when I encounter problems in the future, hahaha.

Guess you like

Origin blog.csdn.net/A33280000f/article/details/121221453