给定一个字符串 s
和一个整数 k
,从字符串开头算起,每计数至 2k
个字符,就反转这 2k
字符中的前 k
个字符。
- 如果剩余字符少于
k
个,则将剩余字符全部反转。 - 如果剩余字符小于
2k
但大于或等于k
个,则反转前k
个字符,其余字符保持原样。
示例 1:
输入:s = "abcdefg", k = 2 输出:"bacdfeg"
示例 2:
输入:s = "abcd", k = 2 输出:"bacd"
提示:
1 <= s.length <= 104
s
仅由小写英文组成1 <= k <= 104
class Solution:
def reverseStr(self, s: str, k: int) -> str:
t = list(s)
for i in range(0, len(t), k << 1):
t[i : i + k] = reversed(t[i : i + k])
return ''.join(t)
class Solution {
public String reverseStr(String s, int k) {
char[] chars = s.toCharArray();
for (int i = 0; i < chars.length; i += (k << 1)) {
for (int st = i, ed = Math.min(chars.length - 1, i + k - 1); st < ed; ++st, --ed) {
char t = chars[st];
chars[st] = chars[ed];
chars[ed] = t;
}
}
return new String(chars);
}
}
class Solution {
public:
string reverseStr(string s, int k) {
for (int i = 0, n = s.size(); i < n; i += (k << 1)) {
reverse(s.begin() + i, s.begin() + min(i + k, n));
}
return s;
}
};
func reverseStr(s string, k int) string {
t := []byte(s)
for i := 0; i < len(t); i += (k << 1) {
for st, ed := i, min(i+k-1, len(t)-1); st < ed; st, ed = st+1, ed-1 {
t[st], t[ed] = t[ed], t[st]
}
}
return string(t)
}