344.Reverse String

Tags: [two_pointers], [string]

Link: https://leetcode.com/problems/reverse-string/\#/description

Write a function that takes a string as input and returns the string reversed.

Example:
Given s = "hello", return "olleh".


Solution: two pointers

class Solution(object):
    def reverseString(self, s):
        """
        :type s: str
        :rtype: str
        """
        if not s:
            return s

        char_arr = list(s)
        left = 0
        right = len(char_arr) - 1

        while left < right:
            char_arr[left], char_arr[right] = char_arr[right], char_arr[left]
            left += 1
            right -= 1

        return ''.join(char_arr)

Note:

  • Time complexity = O(n), n is the length of the given string.

results matching ""

    No results matching ""