算法面试-LeetCode-344. 反转字符串-Python

  • 方法一:执行时间200ms以上,待优化
class Solution(object):
    def reverseString(self, s):
        """
        :type s: List[str]
        :rtype: None Do not return anything, modify s in-place instead.
        """
        left=0
        right=len(s)-1
        while left < right:
            s[left] ,s[right]=s[right],s[left]
            left +=1
            right -=1
        return s

方法二:与方法一差不多

class Solution(object):
    def reverseString(self, s):
        """
        :type s: List[str]
        :rtype: None Do not return anything, modify s in-place instead.
        """
        start = 0
        end = len(s) - 1

        if len(s) % 2 == 0:
            totalSwaps = int(len(s) / 2)
        else:
            totalSwaps = int((len(s) - 1) / 2)

        while totalSwaps > 0:
            s[start], s[end] = s[end], s[start]
            start += 1
            end -= 1
            totalSwaps -= 1


仙衣眠云碧岚袍,一襟潇洒,两袖飘飘。玉墨舒心春酝瓢,行也逍遥,坐也逍遥。
原文地址:https://www.cnblogs.com/max520liuhu/p/11016455.html