From 2ddf04ff1432c5a3f0fdf81061913a5c7fcccd47 Mon Sep 17 00:00:00 2001 From: zhangrunzhe Date: Thu, 24 Oct 2024 18:04:48 +0800 Subject: [PATCH] =?UTF-8?q?=E5=8F=B3=E6=97=8B=E5=AD=97=E7=AC=A6=E4=B8=B2?= =?UTF-8?q?=20swift=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/kamacoder/0055.右旋字符串.md | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/problems/kamacoder/0055.右旋字符串.md b/problems/kamacoder/0055.右旋字符串.md index 363d9ffa..2b32cb44 100644 --- a/problems/kamacoder/0055.右旋字符串.md +++ b/problems/kamacoder/0055.右旋字符串.md @@ -350,7 +350,29 @@ function reverseStr(s, start, end) { ### Swift: +```swift +func rotateWords(_ s: String, _ k: Int) -> String { + var chars = Array(s) + // 先反转整体 + reverseWords(&chars, start: 0, end: s.count - 1) + // 反转前半段 + reverseWords(&chars, start: 0, end: k - 1) + // 反转后半段 + reverseWords(&chars, start: k, end: s.count - 1) + return String(chars) +} +// 反转start...end 的字符数组 +func reverseWords(_ chars: inout [Character], start: Int, end: Int) { + var left = start + var right = end + while left < right, right < chars.count { + (chars[left], chars[right]) = (chars[right], chars[left]) + left += 1 + right -= 1 + } +} +``` ### PHP: