Skip to content

Latest commit

 

History

History
68 lines (47 loc) · 1.24 KB

0344._reverse_string.md

File metadata and controls

68 lines (47 loc) · 1.24 KB

344. Reverse String

难度: Easy

刷题内容

原题连接

内容描述

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

Example 1:

Input: "hello"
Output: "olleh"
Example 2:

Input: "A man, a plan, a canal: Panama"
Output: "amanaP :lanac a ,nalp a ,nam A"

解题方案

思路 1 - 时间复杂度: O(N)- 空间复杂度: O(N)******

因为python不支持item assignment

所以如果非要用two pointer来做的话,那么会是这样

class Solution(object):
    def reverseString(self, s):
        """
        :type s: str
        :rtype: str
        """
        lst = list(s)
        start, end = 0, len(lst) - 1

        while start < end:
            lst[end], lst[start] = lst[start], lst[end]
            start += 1
            end -= 1
        return ''.join(lst)

思路 2 - 时间复杂度: O(N)- 空间复杂度: O(1)******

不要脸的python AC code:

class Solution(object):
    def reverseString(self, s):
        """
        :type s: str
        :rtype: str
        """
        return s[::-1]