[LeetCode] Reverse String II
Posted immjc
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[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:
- The string consists of lower English letters only.
- Length of the given string and k will in the range [1, 10000]
对字符串进行反转,规则是:每隔k个反转k个字母。如果剩下的字母不满足k则,则将剩下的字母全部反转。取t = n / k,将字符串分成k份,每隔一份反转一次。
class Solution { public: string reverseStr(string s, int k) { int n = s.size(), t = n / k; for (int i = 0; i <= t; i++) { if (i % 2 == 0) { if (i * k + k < n) reverse(s.begin() + i * k, s.begin() + i * k + k); else reverse(s.begin() + i * k, s.end()); } } return s; } }; // 6 ms
相关题目:Reverse String
以上是关于[LeetCode] Reverse String II的主要内容,如果未能解决你的问题,请参考以下文章