[英]Reverse a string in-place using recursion
There is a leetcode question on recursion.有一个关于递归的leetcode问题。 Reverse a string, in place, using recursion.
使用递归将字符串原地反转。 Do not allocate an additional array.
不要分配额外的数组。
Write a function that reverses a string.
编写一个反转字符串的 function。 The input string is given as an array of characters char[].
输入字符串以字符数组 char[] 的形式给出。
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
不要为另一个数组分配额外的空间,您必须通过使用 O(1) 额外的 memory 就地修改输入数组来做到这一点。
You may assume all the characters consist of printable ASCII characters.
您可以假设所有字符都由可打印的 ASCII 字符组成。
My solution doesn't work as my slicing operator is creating a copy of the list, rather than being in place.我的解决方案不起作用,因为我的切片操作员正在创建列表的副本,而不是就位。 I can't seem to add a parameter to the function, as the test harness isn't expecting an additional parameter.
我似乎无法向 function 添加参数,因为测试工具不希望有额外的参数。
How do you do this, without an additional parameter to detect the current position index into the string you are trying to reverse, or without an intermediate data structure you append to through the recursive call?如何做到这一点,没有额外的参数来检测当前 position 索引到你试图反转的字符串中,或者没有中间数据结构你 append 通过递归调用?
class Solution:
def reverseString(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
if len(s) <= 1:
return
temp = s[0]
s[0] = s[len(s)-1]
s[len(s)-1] = temp
return self.reverseString(s[1:len(s)-1])
My function with an input of "hello" returns ["o","e","l","l","h"]
.我的 function 输入 "hello" 返回
["o","e","l","l","h"]
。 This is because the first time the function is called it operates on the list in place, and subsequent calls are achieved through a slice of the string.这是因为第一次调用 function 时,它对列表进行就地操作,后续调用是通过字符串的切片实现的。
Thanks all.谢谢大家。 The solution was to add a parameter with a default, to get over the issues with the leetcode test harness, so now I can do it as below:
解决方案是添加一个带有默认值的参数,以解决 leetcode 测试工具的问题,所以现在我可以按如下方式进行:
class Solution:
def reverseString(self, s: List[str], start = 0) -> None:
"""
Do not return anything, modify s in-place instead.
"""
if len(s[start:len(s)-start]) <= 1:
return
end = len(s) - start - 1 # end postition
temp = s[start]
s[start] = s[end]
s[end] = temp
self.reverseString(s, start+1)
Try this尝试这个
chars=list('string')
for i in range((len(chars)-len(chars)%2)//2):
chars[i], chars[-i-1]=chars[-i-1], chars[i]
print(chars)
print(''.join(chars))
From what i understood, the solution should be recursive.据我了解,解决方案应该是递归的。 Try this:
尝试这个:
EDIT: (as should look in leetcode)编辑:(应该在 leetcode 中查看)
def reverseStringHelper(s, index):
length = len(s)
if index >= length / 2:
return
temp = s[index]
s[index] = s[length - 1 - index]
s[length - 1 - index] = temp
reverseString(s, index + 1)
def reverseString(s):
reverseStringHelper(s, 0)
Defining arr = ['h', 'e', 'l', 'l','o']
and calling reverseString(arr, 0)
will result in ['o', 'l', 'l', 'e', 'h']
定义
arr = ['h', 'e', 'l', 'l','o']
并调用reverseString(arr, 0)
将导致['o', 'l', 'l', 'e', 'h']
You may call it from a different function so it would only accept the list.您可以从不同的 function 调用它,因此它只会接受该列表。
This'll pass, since it has to be done in-place :这会过去的,因为它必须就地完成:
from typing import List
class Solution:
def reverseString(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
left, right = 0, len(s) - 1
while left < right:
s[left], s[right] = s[right], s[left]
left, right = left + 1, right - 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.