541. 反转字符串2 Reverse String II

Given a string and an integer k, you need to reverse the first k characters for every 2k characters counting from the start of the string. If there are less 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 left the other as original.
Input: s = "abcdefg", k = 2
Output: "bacdfeg"    
Restrictions:
  1. The string consists of lower English letters only.
  2. Length of the given string and k will in the range [1, 10000]
    1. public class Solution {
    2. public string ReverseStr(string s, int k) {
    3. char[] cArr = s.ToArray();
    4. for (int left = 0; left < cArr.Length; left += 2 * k) {
    5. for (int i = left, j = Math.Min(left + k - 1, cArr.Length - 1); i < j; i++, j--) {
    6. char tmp = cArr[i];
    7. cArr[i] = cArr[j];
    8. cArr[j] = tmp;
    9. }
    10. }
    11. return new string(cArr);
    12. }
    13. }






原文地址:https://www.cnblogs.com/xiejunzhao/p/15d7455a923674663caa30838190afad.html