Merge pull request #1703 from EnzoSeason/master

更新 541. 反转字符串II,优化版本二,提供scala版本的递归解法
This commit is contained in:
程序员Carl
2022-10-25 09:55:49 +08:00
committed by GitHub

View File

@ -399,19 +399,42 @@ object Solution {
}
}
```
版本二: 首先利用sliding每隔k个进行分割随后转换为数组,再使用zipWithIndex添加每个数组的索引紧接着利用map做变换如果索引%2==0则说明需要翻转否则原封不动最后再转换为String
版本二: 首先利用grouped每隔k个进行分割再使用zipWithIndex添加每个数组的索引紧接着利用map做变换如果索引%2==0则说明需要翻转否则原封不动最后再转换为String
```scala
object Solution {
def reverseStr(s: String, k: Int): String = {
s.sliding(k, k)
.toArray
.zipWithIndex
.map(v => if (v._2 % 2 == 0) v._1.reverse else v._1)
// s = "abcdefg", k = 2
s.grouped(k) // Iterator ["ab", "cd", "ef", "g"]
.zipWithIndex // Iterator [("ab", 0), ("cd", 1), ("ef", 2), ("g", 3)]
.map {
case (subStr, index) =>
if (index % 2 == 0) subStr.reverse else subStr
}
.mkString
}
}
```
版本三: (递归)
```scala
import scala.annotation.tailrec
object Solution {
def reverseStr(s: String, k: Int): String = {
@tailrec // 这个函数已经优化成了尾递归
def reverse(s: String, needToReverse: Boolean, history: String): String = {
// 截取前k个字符判断是否翻转
val subStr = if (needToReverse) s.take(k).reverse else s.take(k)
// 如果字符串长度小于k返回结果
// 否则,对于剩余字符串进行同样的操作
if (s.length < k) history + subStr
else reverse(s.drop(k), !needToReverse, history + subStr)
}
reverse(s, true, "")
}
}
```
Rust:
```Rust