LeetCode C++ 541. Reverse String II【String】简单

    科技2025-08-27  12

    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] .

    题意:给定一个字符串 s 和一个整数 k ,你需要对从字符串开头算起的每隔 2k 个字符的前 k 个字符进行反转。如果剩下的字符少于 k 个则全部反转;如果剩余的字符小于 2k 但是大于等于 k 个,则反转前 k 个字符,其余字符不变。


    解法

    看清楚题目后就简单了:

    class Solution { public: string reverseStr(string s, int k) { int n = s.size(), k2 = k * 2, left = 0; if (n < k) { reverse(s.begin(), s.end()); return s; } if (n >= k && n < k2) { reverse(s.begin(), s.begin() + k); return s; } while (left < n) { if (left + k2 <= n) { //剩余字符大于等于2k个 reverse(s.begin() + left, s.begin() + left + k); left += k2; } else if (left + k <= n) { //剩余字符大于等于k个,小于2k个 reverse(s.begin() + left, s.begin() + left + k); break; } else { //剩余字符少于k个 reverse(s.begin() + left, s.end()); break; } } return s; } };

    效率如下:

    执行用时:8 ms, 在所有 C++ 提交中击败了50.63% 的用户 内存消耗:7.1 MB, 在所有 C++ 提交中击败了60.35% 的用户
    Processed: 0.013, SQL: 8