541.Reverse String II(String-Easy)

来源:互联网 发布:app应用市场源码 编辑:程序博客网 时间:2024/05/16 02:07

转载请注明作者和出处: http://blog.csdn.net/c406495762

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]

题目:根据k,反转字符串。

    /**     * 0            k           2k          3k     * |-----------|-----------|-----------|---     * +--reverse--+           +--reverse--+     */

每2k个字符,反转前面的k个字符。如果少于k个字符,反转所有字符。如果大于等于k个字符小于2k个字符,那么反转前面的k个字符,剩余的字符保留不动。

思路:使用reverse函数进行反转。代码依旧很简单。

Language : cpp

class Solution {public:    string reverseStr(string s, int k) {        for(int i = 0; i < s.size(); i += 2*k){            reverse(s.begin()+i, min(s.begin()+i+k, s.end()));        }        return s;    }};
0 0