541. Reverse String II

来源:互联网 发布:archlinux vim python 编辑:程序博客网 时间:2024/04/30 10:22
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.

Example:

Input: s = "abcdefg", k = 2Output: "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]

此题解答主要在于将循环判断条件分清,下面代码分三种情况:
当字符串长度大于2k时,进行前k个字符反转后将指针后移2k;
当字符串长度小于2k大于k时,进行前k个字符反转,结束循环;
当字符串长度小于k时,将剩余字符反转,结束循环;
代码如下:
class Solution {public:void reverse(string& s,int i, int k){char temp;for(int j = 0; j <= (k-i)/2;j++){temp = s[i+j];s[i+j] = s[k-j];s[k-j] = temp;}}    string reverseStr(string s, int k) {        int length = s.length() - 1;        int i = 0;        while(i<length){        if(i+k-1 <= length && i+2*k-1 >= length){        Solution::reverse(s, i, i+k-1);        return s;} else if(i+k-1 >= length && i < length){Solution::reverse(s, i, length);return s;} else if(i+k-1 < length && i + 2*k-1 < length){Solution::reverse(s, i, i+k-1);i = i + 2*k;}}return s;    }};


0 0
原创粉丝点击