当前位置:Gxlcms > JavaScript > Leetcode344--翻转字符串

Leetcode344--翻转字符串

时间:2021-07-01 10:21:17 帮助过:6人阅读

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。

Leetcode344:翻转字符串
编程语言:python

文章目录

  • Leetcode344--翻转字符串
    • 题目描述
    • 解题思路

Leetcode344–翻转字符串

Leetcode344:翻转字符串
编程语言:python

题目描述

原题链接:https://leetcode-cn.com/problems/reverse-string/ (中文)
      https://leetcode.com/problems/reverse-string/ (英文)

题目描述:
编写一个函数,其作用是将输入的字符串反转过来。输入字符串以字符数组char[] 的形式给出。

不要给另外的数组分配额外的空间,你必须原地修改输入数组、使用 O(1)O(1) 的额外空间解决这一问题。

你可以假设数组中的所有字符都是 ASCII码表中的可打印字符。

示例1:

输入:[“h”,“e”,“l”,“l”,“o”]
输出:[“o”,“l”,“l”,“e”,“h”]

示例2:

输入:[“H”,“a”,“n”,“n”,“a”,“h”]
输出:[“h”,“a”,“n”,“n”,“a”,“H”]

解题思路

方法1:
使用双指针方法,从首尾往中间靠拢,相遇时交换完成

def reverseString(self, s: List[str]) -> None:
	"""
	Do not return anything, modify s in-place instead.
	"""
	length = len(s)
	half = len(s) // 2
	
	# 建立一个tmp临时变量,用于缓存数组着中的元素
	for i in range(half):
	    tmp = s[i]
	    s[i] = s[length-i-1]
	    s[length-i-1] = tmp 

python可以同时给多个变量赋值,上述代码可以改写为:

def reverseString(self, s):
	"""
	:type s: List[str]
	:rtype: void Do not return anything, modify s in-place instead.
	"""
	length = len(s)
	half = l//2
	for i in range(half):
	    s[i], s[length-i-1] = s[length-i-1], s[i]

方法2:
使用python内置函数

def reverseString(self, s):
	"""
	:type s: List[str]
	:rtype: void Do not return anything, modify s in-place instead.
	"""
	s.reverse()

方法3:
使用pop方法,每次循环删除第一元素,然后插入到指定的位置
每次删除原字符串改变一位,最新的需要翻转的字符变为第一个字符,循环n1n-1次后完成翻转。

def reverseString(self, s):
	"""
	:type s: List[str]
	:rtype: void Do not return anything, modify s in-place instead.
	"""
	n = len(s)
	for i in range(n-1):
	    t = s.pop(0)
	    s.insert(n-i-1, t)

人气教程排行