mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-10 20:40:39 +08:00
Update 0541.反转字符串II.md
This commit is contained in:
@ -399,14 +399,17 @@ object Solution {
|
||||
}
|
||||
}
|
||||
```
|
||||
版本二: 首先利用sliding每隔k个进行分割,随后转换为数组,再使用zipWithIndex添加每个数组的索引,紧接着利用map做变换,如果索引%2==0则说明需要翻转,否则原封不动,最后再转换为String
|
||||
版本二: 首先利用grouped每隔k个进行分割,再使用zipWithIndex添加每个数组的索引,紧接着利用map做变换,如果索引%2==0则说明需要翻转,否则原封不动,最后再转换为String
|
||||
```scala
|
||||
object Solution {
|
||||
object SolutionFunc {
|
||||
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
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user