- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
我正在从 leetcode 的特色教程中学习递归基础知识 Recursion I
第一个练习是反转字符串 Reverse String - LeetCode
Write a function that reverses a string. The input string is given as an array of characters
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.
You may assume all the characters consist of printable ascii characters.
Example 1:
Input: ["h","e","l","l","o"]
Output: ["o","l","l","e","h"]Example 2:
Input: ["H","a","n","n","a","h"]
Output: ["h","a","n","n","a","H"]
公认的解决方案是
class Solution:
def reverseString(self, s):
"""
:type s: str
:rtype: str
"""
#base case
if len(s) <= 1:
return s
#recur case
elif len(s) >= 2:
n=len(s)
return self.reverseString(s[n//2:])+self.reverseString(s[:n//2])
解决方案的两个问题:
1、不就地修改
2、递归地对字符串进行切片是很昂贵的。
作为改进的第一步,引入参数lo
和hi
来存储索引
class Solution:
def reverseString(self, s, lo=0, hi=None):
"""
:type s: str
:rtype: None
"""
if hi == None:
hi = len(s)
#base case
if hi <= 1:
return s
#recur case
elif hi >= 2:
mid = hi // 2
left = self.reverseString(s, lo, mid)
right = self.reverseString(s, mid, hi)
return left + right
报错
RecursionError: maximum recursion depth exceeded in comparison
Ran 1 test in 0.005s
W 有什么问题吗?
最佳答案
要在没有空间的情况下执行此操作,您需要交换。您不能添加数组切片。而不是在中间拆分索引,这永远不会让您交换相反的对(在基本情况下除外)。
如果您直观地想象递归,就可以看到它。你从一个像这样的列表开始:
1, 2, 3, 4
^ ^ <-- these need to swap in a reverse
但是在你第一次递归调用之后,你把它分成了:
---- | ----
1, 2 3, 4
^ ^ <-- these still need to be swapped, bu when?
现在分支一无法到达分支二中的 4 进行交换,除非在递归展开时有一种不明显的方法来进行交换。
相反,您可以(更容易地)从两端引导索引并边走边交换。那么你的基本情况就是他们在中间相遇的时候:
class Solution:
def reverseString(self, s, lo=0, hi=None):
if hi == None:
hi = len(s) - 1
if hi <= lo:
return s
s[lo], s[hi] = s[hi], s[lo]
return self.reverseString(s, lo + 1, hi - 1)
s = Solution()
s.reverseString([1, 2, 3, 4])
# [4, 3, 2, 1]
s.reverseString([1, 2, 3, 4, 5])
#[5, 4, 3, 2, 1]
关于python - 反转字符串的就地递归解决方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55717930/
我正在尝试解决以下问题: We are given an array containing ‘n’ objects. Each object, when created, was assigned a
考虑以下代码: a=(1 2 3) a='seven' export a declare -p a 输出(来自declare)是: declare -ax a='([0]="seven" [1]="2
我正在尝试将 ['1','2','3','4'] 转换为 [1,2,3,4]我想就地进行此转换。有可能做到吗?如果不是,最佳解决方案是什么。 最佳答案 我觉得用map比较好对于这类任务。这会创建迭代器
好的,所以我之前发布了关于尝试(没有任何预建函数)删除额外空间的信息 "this is a test"会回来的 "this is a test" Remove spaces from a strin
我有一个名为Media的插件,该插件应负责图像大小调整等工作。 它具有以下依赖性: dependencies { compile group: 'org.ccil.cowan.tagsoup'
我需要将一个大字符串向左“移动”X 个空格。它太大了,无法放入内存,所以我需要就地做。我需要使用最少量的系统调用来完成此操作。 我知道我可以使用缓冲区并重用内存来最大限度地减少内存消耗,然后使用 fs
我想知道是否可以在不需要临时数组的情况下通过 Cholesky 分解获得矩阵的逆。截至目前,我可以在不使用临时数组的情况下进行 cholesky 分解,但从那里我还没有想出一种方法来获得原始矩阵的逆矩
是否有任何用于 Javascript 的就地编辑插件..像 firebug 之类的东西,它对即时 CSS 编辑和预览非常有用,但不允许就地 JS 编辑..那么,有没有我们可以立即更新和更新的工具或插件
题目如下:给定一个 linked list,将备用 indices 移到 list 的后面 例如: input: : [0] -> [1] -> [2] -> [3] -> [4]
在我看来,std::copy_if 对于过滤容器非常有用: std::vector vec { 1, 2, 3, 4 }; auto itEnd = std::copy_if(vec.begin(),
在 C++ 中相交两个集合的标准方法是执行以下操作: std::set set_1; // With some elements std::set set_2; // With some othe
在 Python 中,字符串是不可变的。 逐个字符遍历字符串并对其进行修改的标准习语是什么? 我能想到的唯一方法是一些与加入结果字符串相关的真正臭名昭著的黑客攻击。 -- 在 C 中: for(i
我有一个 ListBuffer。我想删除满足特定条件的所有元素。 我可以迭代它并删除每个元素。但是 Scala 对改变你正在迭代的列表有什么看法呢?它会起作用,还是会删除错误的元素/不返回所有元素?
我需要重新绑定(bind)两个大数据帧。现在我用的是 df 根据 nikola 的评论,这里是 ?rbindlist 的描述(v1.8.2 中的新增功能): Same as do.call("rbi
关闭。此题需要details or clarity 。目前不接受答案。 想要改进这个问题吗?通过 editing this post 添加详细信息并澄清问题. 已关闭 3 年前。 Improve th
我在带有 LVS_EDITLABELS 的无模式 Win32 对话框中有一个小图标模式的 ListView 放。无论编辑是通过单击鼠标还是通过调用 ListView_LabelEdit() 以编程方式
所以基本上不能/允许创建一个新数组。除了实际更改和操作当前数组外,无法返回任何内容。您如何获取字符数组并简单地翻转/反转它们。 Starting array: ['P','e','r','f','e'
我不明白为什么下面的代码没有对 vector 的前两个元素进行排序: int main() { std::vector v = {2,1,3,1,2}; std::sort(v.beg
我有以下(简化的)代码: a = a[::3] b = b[::3] c = c[::3] d = d[::3] a,b,c,d,其实都是很复杂的表达式,所以我想这样写: for l in [a, b
可以对数组进行不依赖于数组秩的操作。迭代器也不总是合适的解决方案。给定数组 double[,] myarray = new double[10,5]; 实现以下工作流程是可取的: 将 Rank>1 的
我是一名优秀的程序员,十分优秀!