From 77b431d27618a202d90b5bfc420b6686cbc66312 Mon Sep 17 00:00:00 2001 From: Jijie LIU Date: Wed, 19 Oct 2022 22:20:01 +0200 Subject: [PATCH] =?UTF-8?q?Update=200541.=E5=8F=8D=E8=BD=AC=E5=AD=97?= =?UTF-8?q?=E7=AC=A6=E4=B8=B2II.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0541.反转字符串II.md | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/problems/0541.反转字符串II.md b/problems/0541.反转字符串II.md index 02ad92a0..f38ac042 100644 --- a/problems/0541.反转字符串II.md +++ b/problems/0541.反转字符串II.md @@ -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 } }