llllmz

导航

541. 反转字符串 II

 

class Solution {
public:
    string reverseStr(string s, int k) {
        for(int i = 0; i < s.size(); i += 2*k){
            if(s.size() - i >= k){
                reverse(s, i, i + k -1);
            }else{
                reverse(s, i, s.size() - 1);
            }
        }
        return s;
    }

    void reverse(string& s, int head, int tail){
        while(head < tail){
            char temp = s[head];
            s[head] = s[tail];
            s[tail] = temp;
            ++head;
            --tail;
        }
    }
};

 

posted on 2024-10-14 23:05  神奇的萝卜丝  阅读(9)  评论(0)    收藏  举报