Update 0541.反转字符串II.md

This commit is contained in:
Jijie LIU
2022-10-19 22:20:01 +02:00
committed by GitHub
parent 9977fb5996
commit 77b431d276

View File

@ -399,14 +399,17 @@ object Solution {
} }
} }
``` ```
版本二: 首先利用sliding每隔k个进行分割随后转换为数组,再使用zipWithIndex添加每个数组的索引紧接着利用map做变换如果索引%2==0则说明需要翻转否则原封不动最后再转换为String 版本二: 首先利用grouped每隔k个进行分割再使用zipWithIndex添加每个数组的索引紧接着利用map做变换如果索引%2==0则说明需要翻转否则原封不动最后再转换为String
```scala ```scala
object Solution { object SolutionFunc {
def reverseStr(s: String, k: Int): String = { def reverseStr(s: String, k: Int): String = {
s.sliding(k, k) // s = "abcdefg", k = 2
.toArray s.grouped(k) // Iterator ["ab", "cd", "ef", "g"]
.zipWithIndex .zipWithIndex // Iterator [("ab", 0), ("cd", 1), ("ef", 2), ("g", 3)]
.map(v => if (v._2 % 2 == 0) v._1.reverse else v._1) .map {
case (subStr, index) =>
if (index % 2 == 0) subStr.reverse else subStr
}
.mkString .mkString
} }
} }