美文网首页Leetcode
Leetcode 541. Reverse String II

Leetcode 541. Reverse String II

作者: SnailTyan | 来源:发表于2018-10-14 15:09 被阅读5次

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

1. Description

Reverse String II

2. Solution

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

    本文链接:https://www.haomeiwen.com/subject/gjnzaftx.html