leetcode 541. Reverse String II 反转字符串

清疚 2022-06-03 03:40 266阅读 0赞

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]

本题题意十分简单,就是做一个字符串的反转,注意是没2k个子串中前k个反转,其余的不变

建议和leetcode 344. Reverse String 反转字符串 一起学习

代码如下:

  1. #include <iostream>
  2. #include <vector>
  3. #include <map>
  4. #include <set>
  5. #include <queue>
  6. #include <stack>
  7. #include <string>
  8. #include <climits>
  9. #include <algorithm>
  10. #include <sstream>
  11. #include <functional>
  12. #include <bitset>
  13. #include <numeric>
  14. #include <cmath>
  15. using namespace std;
  16. class Solution
  17. {
  18. public:
  19. string reverseStr(string s, int k)
  20. {
  21. int count = s.length() / k;
  22. for (int i = 0; i <= count; i++)
  23. {
  24. if (i % 2 == 0)
  25. {
  26. if (i*k + k < s.length())
  27. reverse(s.begin()+i*k,s.begin() + i*k+k);
  28. else
  29. reverse(s.begin() + i*k, s.end());
  30. }
  31. }
  32. return s;
  33. }
  34. };

发表评论

表情:
评论列表 (有 0 条评论,266人围观)

还没有评论,来说两句吧...

相关阅读

    相关 541. 字符串 II

    给定一个字符串 s 和一个整数 k,从字符串开头算起,每 2k 个字符反转前 k 个字符。 如果剩余字符少于 k 个,则将剩余字符全部反转。 如果剩余字符小于 2k 但大

    相关 LeetCode541. 字符串 II

    给定一个字符串和一个整数 k,你需要对从字符串开头算起的每个 2k 个字符的前k个字符进行反转。如果剩余少于 k 个字符,则将剩余的所有全部反转。如果有小于 2k 但大于或等于

    相关 541. 字符串 II

    给定一个字符串和一个整数 k,你需要对从字符串开头算起的每个 2k 个字符的前k个字符进行反转。如果剩余少于 k 个字符,则将剩余的所有全部反转。如果有小于 2k 但大于或等于