Problem
题目大意:把字符串分成块,每块长度2k,单独反转每一块的前k的字符。
https://leetcode.com/problems/reverse-string-ii/description/
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]
Solution
C++
1 2 3 4 5 6 7 8 9 10 11 |
// Author: Huahua // Running time: 9 ms class Solution { public: string reverseStr(string s, int k) { const int n = s.length(); for (int i = 0; i <= n / k; i += 2) std::reverse(s.begin() + i * k, s.begin() + min(n, (i + 1) * k)); return s; } }; |
Related Problems
请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.
Be First to Comment