LeetCode Reverse String II

LeetCode Reverse String II 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:
  1. The string consists of lower English letters only.
  2. Length of the given string and k will in the range [1, 10000]

LeetCode Reverse String的基础上,稍微增加了一点难度,要求每2k个字母逆序其前k个字母。当剩余字母少于k个时,都逆序。当剩余字母在k个~2k个之间时,逆序前k个。 直接借用STL的reverse函数,迭代器的结束位置为min(s.begin() + start + k,s.end()),因为string是线性存储的,其迭代器可以比较大小。 代码如下: [cpp] class Solution { public: string reverseStr(string s, int k) { int n = s.size(); for (int start = 0; start < n; start += 2 * k) { reverse(s.begin() + start, min(s.begin() + start + k,s.end())); } return s; } }; [/cpp] 本代码提交AC,用时9MS。]]>

1 thought on “LeetCode Reverse String II

  1. Pingback: LeetCode Reverse String II | nce3xin_code

Leave a Reply

Your email address will not be published. Required fields are marked *