Reverse String(Easy)

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

Python 3 Code

The solution converts the string into list before using double pointers to perform the classic approach of swapping of first and last elements. Finally, it joins the list elements to return a string.

class Solution:
    def reverseString(self, s):
        if not s or len(s) < 2:
            return s

        slist = list(s)
        start, end = 0, len(slist)-1

        while start < end:
            slist[start], slist[end] = slist[end], slist[start]
            start += 1
            end -= 1

        return ''.join(slist)

test =  Solution()
print(test.reverseString("Beijing at office"))

results matching ""

    No results matching ""