LeetCode 541. Reverse String II

来源:互联网 发布:nginx负载均衡测试 编辑:程序博客网 时间:2024/05/18 02:29

题目:
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 = 2
Output: “bacdfeg”
Restrictions:
The string consists of lower English letters only.
Length of the given string and k will in the range [1, 10000]

思路:
每2k个字符是一组,进行处理。
若剩下的字符小于k个,则逆序所有字符,直接返回s;
若剩下的字符大于等于k且小于2k个,则逆序前k个字符,直接返回s;
若剩下的字符大于2k个,则逆序前k个字符后,再将索引i往后移动2*k位。
循环结束后,如果没有返回,这种情况是字符串长度刚好是2k的倍数,则再返回s。

代码:

class Solution {public:    string reverseStr(string s, int k) {        int len=s.length();        if(len<=2){//如果s的长度小于等于2,直接返回s            return s;        }        int i=0;//设置索引i        while(i<len){//如果索引i小于len时            if(i+k-1>=len){//如果剩下的字符小于k个                reverse(s.begin()+i,s.end());//逆序所有剩下字符                return s;//直接返回s            }            else if(i+k-1<=len&&i+2*k-1>=len){//剩下的字符大于等于k且小于2k个                reverse(s.begin()+i,s.begin()+i+k);//则逆序前k个字符                return s;//直接返回s            }             else{//其实是如果剩下的字符大于2k个                reverse(s.begin()+i,s.begin()+i+k);//则逆序前k个字符                i+=2*k;//索引i往后移动2*k位            }        }        return s;//这种情况是字符串长度刚好是2k的倍数    }};

**输出结果:**9ms

0 0
原创粉丝点击