|
| 1 | +/** |
| 2 | + Given a string s and an integer k, reverse the first k characters for every 2k characters counting from the start of the string. |
| 3 | + |
| 4 | + If there are fewer than k characters left, reverse all of them. If there are less than 2k but greater than or equal to k characters, then reverse the first k characters and leave the other as original. |
| 5 | + |
| 6 | + |
| 7 | + |
| 8 | + Example 1: |
| 9 | + Input: s = "abcdefg", k = 2 |
| 10 | + Output: "bacdfeg" |
| 11 | + |
| 12 | + Example 2: |
| 13 | + Input: s = "abcd", k = 2 |
| 14 | + Output: "bacd" |
| 15 | + |
| 16 | + |
| 17 | + Constraints: |
| 18 | + - 1 <= s.length <= 10^4 |
| 19 | + - s consists of only lowercase English letters. |
| 20 | + - 1 <= k <= 10^4 |
| 21 | + */ |
| 22 | +class Solution { |
| 23 | + func reverseStr(_ s: String, _ k: Int) -> String { |
| 24 | + if s.count <= k { |
| 25 | + return String(s.reversed()) |
| 26 | + } else { |
| 27 | + var result = s |
| 28 | + let quotient = s.count / (2 * k) |
| 29 | + let remiander = s.count % (2 * k) |
| 30 | + if quotient > 0 { |
| 31 | + for i in 0..<quotient { |
| 32 | + let subString = String(s[s.index(s.startIndex, offsetBy: i * 2 * k)..<s.index(s.startIndex, offsetBy: i * 2 * k + k)].reversed()) |
| 33 | + result.replaceSubrange(s.index(s.startIndex, offsetBy: i * 2 * k)..<s.index(s.startIndex, offsetBy: i * 2 * k + k), with: subString) |
| 34 | + } |
| 35 | + } |
| 36 | + if remiander > 0 { |
| 37 | + if remiander >= k { |
| 38 | + let subString = String(s[s.index(s.startIndex, offsetBy: quotient * 2 * k)..<s.index(s.startIndex, offsetBy: quotient * 2 * k + k)].reversed()) |
| 39 | + result.replaceSubrange(s.index(s.startIndex, offsetBy: quotient * 2 * k)..<s.index(s.startIndex, offsetBy: quotient * 2 * k + k), with: subString) |
| 40 | + } else { |
| 41 | + let subString = String(s[s.index(s.startIndex, offsetBy: quotient * 2 * k)...s.index(s.startIndex, offsetBy: s.count - 1)].reversed()) |
| 42 | + result.replaceSubrange(s.index(s.startIndex, offsetBy: quotient * 2 * k)...s.index(s.startIndex, offsetBy: s.count - 1), with: subString) |
| 43 | + } |
| 44 | + } |
| 45 | + return result |
| 46 | + } |
| 47 | + } |
| 48 | +} |
| 49 | + |
| 50 | +let s = Solution() |
| 51 | +let r = s.reverseStr("abcd", 2) |
| 52 | +print(r) |
0 commit comments