Leetcode 541. Reverse String II

文章作者:Tyan
博客:noahsnail.com  |  CSDN  | 

1. Description

Leetcode 541. Reverse String II_第1张图片
Reverse String II

2. Solution

  • Version 1
class Solution {
public:
    string reverseStr(string s, int k) {
        int index = 0;
        int range = 2 * k;
        while(index < s.length()) {
            reverse(s, index, min(index + k - 1, int(s.length() - 1)));
            index += range;
        }
        return s;
    }
    
private:
    void reverse(string& s, int start, int end) {
        while(start < end) {
            swap(s[start++], s[end--]);
        }
    }
    
    void swap(char& a, char& b) {
        char temp = a;
        a = b;
        b = temp;
    }
};
  • Version 2
class Solution {
public:
    string reverseStr(string s, int k) {
        int index = 0;
        int range = 2 * k;
        while(index < s.length()) {
            reverse(s, index, min(index + k - 1, int(s.length() - 1)));
            index += range;
        }
        return s;
    }
    

     
private:
    void reverse(string& s, int start, int end) {
        while(start < end) {
            swap(s[start++], s[end--]);
        }
    }
    
    void swap(char& a, char& b) {
        char temp = a;
        a = b;
        b = temp;
    }
};

Reference

  1. https://leetcode.com/problems/reverse-string-ii/description/

你可能感兴趣的:(Leetcode 541. Reverse String II)