LeetCode 541. Reverse String II (字符串翻转)

来源:互联网 发布:火炬之光 mac人物存档 编辑:程序博客网 时间:2024/06/06 20: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]

输入字符串s和正整数k,对于每2k个字母,将其中前k个字母翻转。最后如果剩余字母少于k个,则将其全部翻转;若多于k个,则将前k个翻转,其余不变。

思路:利用void reverse(str.begin(),str.end())函数直接原位翻转,若要翻转到其他变量,可使用str2.assign(str.rbegin(), str.rend())函数。


    string reverseStr(string s, int k) {        int left = s.size()%(2*k);        int i;                if (left<k)        {            for(i=0;i<s.size()-left;i+=(2*k))                reverse(s.begin()+i,s.begin()+i+k);            reverse(s.begin()+i,s.end());        }        else        {            for(i=0;i<s.size()-left;i+=(2*k))                reverse(s.begin()+i,s.begin()+i+k);            reverse(s.begin()+i,s.begin()+i+k);        }        return s;    }


原创粉丝点击