LeetCode #344.反转字符串

力扣 | 344.反转字符串

LeetCode #344.反转字符串_第1张图片

 方法:双指针

简单题重拳出击!

直接用双指针,从两边往中间移动,交换左右指针指向的元素,完成反转。

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

完整测试代码

from typing import List

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

class main:
    a = Solution()
    s = ["h","e","l","l","o"]
    print(s)
    b=a.reverseString(s)
    print(s)


if __name__ == '__main__':
    main()

你可能感兴趣的:(leetcode,算法,职场和发展,python)