首页 > 代码库 > [leetcode-541-Reverse String II]
[leetcode-541-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:
The string consists of lower English letters only.
Length of the given string and k will in the range [1, 10000]
思路:
以2*k 为一组,每一组前k个字符翻转,然后处理剩余字符。
写出来感觉好啰嗦。。另外简洁的代码看到大神有用stl的reverse的,回头试一下,省不少事儿。
string reverseStr(string s, int k) { int group = s.size()/(2*k); int i = 0; for (; i < group;i++) { for (int j = 0; j < k/2;j++) { swap(s[i * 2 * k + j], s[i * 2 * k + k-j-1]); } } int remain = s.size() % (2 * k); int end = (remain >= k) ? k : remain ; for (int j = 0; j < end/2;j++) { swap(s[i * 2 * k + j], s[i * 2 * k + end - j - 1]); } return s; }
[leetcode-541-Reverse String II]
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。